Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases

Guilherme Mergulhao
Guilherme Mergulhao
4,002 Points

Double count result when using INNER JOIN on TSQL

Hello all,

Im using the following query to count all scripts runs, but when there are 2 types of run for each software, it doubles the count result.

Here is query I'm using:

SELECT p.produto, p.pacote, COUNT(p.produto) AS Execuções, CONVERT(varchar, AVG(DATEDIFF(SECOND, p.inicio, p.fim)) / 60) + ':' + RIGHT('0' + CONVERT(varchar, AVG(DATEDIFF(SECOND, p.inicio, p.fim)) % 60), 2) AS [Tempo Médio (Automatizado)], t.tempo_minutos AS [Tempo Médio (Manual)], CONVERT(varchar, (t.tempo_minutos * 60 - AVG(DATEDIFF(SECOND, p.inicio, p.fim))) / 60) + ':' + RIGHT('0' + CONVERT(varchar, (t.tempo_minutos * 60 - AVG(DATEDIFF(SECOND, p.inicio, p.fim))) % 60), 2) AS [Economia Média], CONVERT(varchar, (t.tempo_minutos * 60 - AVG(DATEDIFF(SECOND, p.inicio, p.fim))) * COUNT(p.produto) / 60)  + ':' + RIGHT('0' + CONVERT(varchar, (t.tempo_minutos * 60 - AVG(DATEDIFF(SECOND, p.inicio, p.fim))) * COUNT(p.produto) % 60), 2) AS [Economia Total]
FROM [log].pdq AS p 
INNER JOIN infra.tempo_medio_execucao AS t ON t.produto = p.produto
WHERE (p.equipamento NOT LIKE 'XXX%') AND (p.status IS NOT NULL) AND (p.status = 'Sucesso')
GROUP BY p.produto, p.pacote, t.tempo_minutos

Its retuning the following information: (Removed the unnecessary info from the table)

produto ---- pacote -------- Execuções

SafeSign --- Desinstalação - 6

SafeSign --- Instalação ---- 18

ScanBack --- Instalação ---- 128

Where it should return:

produto ---- pacote -------- Execuções

SafeSign --- Desinstalação - 3

SafeSign --- Instalação ---- 9

ScanBack --- Instalação ---- 128

-- Thanks in advance!

1 Answer

Steven Parker
Steven Parker
230,274 Points

It's not clear why you are expecting a different result than what you get. We'd need to see the contents of the tables to understand.

But it could be that the grouping is causing more rows to participate in the aggregates than you anticipate.