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.
I don’t have a way of testing it but I think this should give you what you are looking for: