I’ve read close to a dozen similar issues on this site, but I don’t think my specific case was covered anywhere. I’m not a dba, this is just a side-project I was voluntold for because I knew more SQL than anyone else here, so I won’t take it personally if somebody tells me this query is a disaster. 🙂
This is my query:
SELECT COUNT(a.issue_type_id) as DistinctIssues, b.issue_type_name, c.subissue_type_name, null AS DistinctTickets
FROM [somedb].[dbo].[wh_task] AS a
INNER JOIN [somedb].[dbo].[wh_issue_type] AS b ON a.issue_type_id = b.issue_type_id
INNER JOIN [somedb].[dbo].[wh_subissue_type] AS c ON a.subissue_type_id = c.subissue_type_id
WHERE a.[create_time] between '11/01/12' AND '01/31/13'
AND a.[account_id] = 123456
AND a.[account_contact_id] is not null
GROUP BY b.issue_type_name, c.subissue_type_name
UNION
SELECT null as DistinctIssues, b.issue_type_name, c.subissue_type_name, COUNT(a.issue_type_id) as DistinctTickets
FROM [somedb].[dbo].[wh_task] AS a
INNER JOIN [somedb].[dbo].[wh_issue_type] AS b ON a.issue_type_id = b.issue_type_id
INNER JOIN [somedb].[dbo].[wh_subissue_type] AS c ON a.subissue_type_id = c.subissue_type_id
WHERE a.[create_time] between '11/01/12' AND '01/31/13'
AND a.[account_id] = 123456
GROUP BY b.issue_type_name, c.subissue_type_name
And the results look like this.
DistinctIssues issue_type_name subissue_type_name DistinctTickets
NULL Storage EMC 45
NULL Storage HP 2
NULL Symantec Anti Virus 1
NULL Symantec Backup Exec 4
NULL Virtualization Environmental 1
NULL Virtualization Network 5
1 Microsoft Server 2003 NULL
1 Microsoft Windows 7 NULL
1 Network Performance NULL
1 Virtualization Environmental NULL
2 Exchange Database NULL
I bet you can guess what I’m trying to do from here.
I’m grouping by the two issue types, and I want the count of all tickets, as well as the count of a subset of those tickets. My database is a MS SQL server (2008, I believe). I only have access to views, for what that’s worth.
Both queries join the same tables on the same criteria, group the results on the same criteria and even count the same column. The only difference appears to be that one of the queries is using an additional condition in the WHERE clause.
In that case, you can combine them into a single query, using conditional aggregation for the value returned by the query with the additional condition (
DistinctIssues):