I am having difficulty with this. This query worked fine in calculating the sums until I put the first inner join in. In the table tbl_companies there are multiple entries per company, for example the table could look like this:
priority company externalip
1 bla 9.9.9.9
1 bla 3.3.3.3
1 company2 3.56.6.6
In the below query the sum (that calculates As TotalWithoutNew and TotalAllId is doubling when there is more than one entry for the company, and tripling if there is three etc. What I want it to do is simply bring back the priority from the table tbl_companies
SELECT b.company,
b.priority,
i.concom,
Coalesce (SUM(CASE
WHEN c.category_id = '30' THEN 0
ELSE t.logmins
END), 0) AS totalwithoutnew,
Coalesce (SUM(t.logmins), 0) AS totalallid
FROM helpdesk3.dbo.inquiry AS i
INNER JOIN [Check].[dbo].[tbl_companies] AS b
ON i.concom = b.company COLLATE sql_latin1_general_cp1_ci_as
INNER JOIN timelog AS t
ON t.inquiry_id = i.inquiry_id
INNER JOIN prod AS p
ON i.prod_id = p.prod_id
INNER JOIN category AS c
ON p.category_id = c.category_id
WHERE ( Datepart(yyyy, escdate) = 2011 )
GROUP BY i.concom,
b.company,
b.priority
ORDER BY totalwithoutnew DESC,
b.priority DESC
You should split the query to avoid multiple results from tbl_companies.