I have a query that totals up all cases that were active on 01/01/2010.
SELECT COUNT(CaseID) AS Total
FROM dbo.ClientCase
WHERE (CaseStartDate <= CONVERT(DATETIME, '2010-01-01 00:00:00', 102)) AND (CaseClosedDate >= CONVERT(DATETIME, '2010-01-01 00:00:00', 102)) OR (CaseClosedDate IS NULL)
GROUP BY CaseStartDate
I also have a Calendar table that I can use to create a query that returns 12 dates starting from 1st Jan, 1st Feb, 1st Mar thru to 1st Dec.
I can't work out how to combine the 2 queries so I get a count of all of the Case totals for the 1st of each month.
I need to see something like
Month Total
Jan 102
Feb 130
Mar 145
.....
Dec 162
If you only want a total count of sales every month, then you can use COUNT function instead. mysql> select year(order_date),month(order_date),sum(sale) from sales WHERE condition group by year(order_date),month(order_date) order by year(order_date),month(order_date);
SELECT department, SUM(sales) AS "Total sales" FROM order_details GROUP BY department; Because you have listed one column in your SQL SELECT statement that is not encapsulated in the SQL SUM function, you must use the SQL GROUP BY clause. The department field must, therefore, be listed in the SQL GROUP BY section.
SELECT cal.MonthName, COUNT(CaseID) AS Total
FROM dbo.calendarTable cal
LEFT OUTER JOIN dbo.ClientCase cc
ON Month(cal.MonthStartDate) = Month(CaseStartDate)
WHERE
(CaseStartDate <= CONVERT(DATETIME, cal.MonthStartDate, 102)) AND
(CaseClosedDate >= CONVERT(DATETIME, cal.MonthStartDate, 102)) OR
(CaseClosedDate IS NULL)
GROUP BY cal.MonthName
Assuming Calendar has two columns such as MonthName
and FirstDate
, you want s/thing like
SELECT Calendar.MonthName AS Month, COUNT(ClientCase.CaseId) AS Total,
FROM ClientCase
JOIN Calendar
ON (MONTH(Calendar.FirstDate) = MONTH(ClientCase.CaseStartDate))
GROUP BY Calendar.MonthName
You could just simply group by the month of the query:
SELECT
MONTH(CaseStartDate), COUNT(CaseID) AS Total
FROM
dbo.ClientCase
WHERE
(CaseStartDate <= CONVERT(DATETIME, '2010-01-01 00:00:00', 102))
AND (CaseClosedDate >= CONVERT(DATETIME, '2010-01-01 00:00:00', 102)) OR
(CaseClosedDate IS NULL)
GROUP BY
MONTH(CaseStartDate)
That should give you an output that's quite close (numerical months instead of Jan, Feb etc. - but close enough).
With this additional step, you'll get the first three letter's of each month's name:
SELECT
SUBSTRING(DATENAME(MONTH, CaseStartDate), 1, 3) AS 'Month',
COUNT(CaseID) AS Total
FROM
dbo.ClientCase
WHERE
(CaseStartDate <= CONVERT(DATETIME, '2010-01-01 00:00:00', 102))
AND (CaseClosedDate >= CONVERT(DATETIME, '2010-01-01 00:00:00', 102)) OR
(CaseClosedDate IS NULL)
GROUP BY
MONTH(CaseStartDate), SUBSTRING(DATENAME(MONTH, CaseStartDate), 1, 3)
ORDER BY
MONTH(CaseStartDate)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With