Reputation: 992
Currently, I have 2 queries:
SELECT dateadd(month, x.MonthOffset,0) as [Month], SUM(x.itemcount) as [Total] FROM ( SELECT datediff(month,0, cna.impdate) as MonthOffset, count(*) as itemcount FROM myTable WHERE (emergency = 'Emergency') AND (impdate BETWEEN '" + fromDate + "' AND '" + toDate + "') GROUP BY impdate ) x GROUP BY MonthOffset ORDER BY MonthOffset asc SELECT dateadd(month, x.MonthOffset,0) as [Month], SUM(x.itemcount) as [Total] FROM ( SELECT datediff(month,0, cna.impdate) as MonthOffset, count(*) as itemcount FROM myTable WHERE (impdate BETWEEN '" + fromDate + "' AND '" + toDate + "') GROUP BY impdate ) x GROUP BY MonthOffset ORDER BY MonthOffset asc
This will return 2 columns of data with a monthly count of items.
My problem occurs when there exists a month without an emergency item. Because I pass the object through to the second query, if the number of columns retrieved from the first does not match the second, I will receive an index out of bounds error.
How can I join my two queries together so that I can have 3 columns - month, emergency total and item total? Emergency total can be 0 or null.
Upvotes: 1
Views: 113
Reputation: 1703
I don't have a way of testing it but I think this should give you what you are looking for:
SELECT dateadd(month, datediff(month,0, cna.impdate),0) as [Month],
count(*) as itemcount,
SUM(CASE WHEN emergency = 'Emergency' THEN 1 ELSE 0 END) AS EmergencyCount
FROM myTable
WHERE impdate BETWEEN '" + fromDate + "' AND '" + toDate + "'
GROUP BY dateadd(month, datediff(month,0, cna.impdate),0)
ORDER BY [Month] asc
Upvotes: 6