我想按月計算活動數,並按部門名稱對其進行分組。該報告基於我輸入查詢「@rptDate」的日期參數。我在下面的工作,但我猜測有一個更好的方式做同樣的事情,並希望有人可以擺脫一些光。我需要獲得按部門分組的月份活動數
Select Count(*) As Month1Count, 0 As Month2Count, 0 As Month3Count,
0 As Month4Count, 0 as Month5Count, 0 as Month6Count, 0 as Month7Count,
0 as Month8Count, 0 as Month9COunt, 0 as Month10Count, 0 as Month11Count,
0 as Month12Count, DepartmentName,ActivityDescription
from reports.WorkOrders
WHERE Month(BeginDate) = Month(@rptDate) and Year(BeginDate) = Year(@rptDate)
Group By DepartmentName, ActivityDescription
UNION
Select 0 As Month1Count, COUNT(*) As Month2Count, 0 as Month3Count,
0 as Month4Count, 0 as Month5Count, 0 as Month6Count, 0 as Month7Count,
0 as Month8Count, 0 as Month9COunt, 0 as Month10Count, 0 as Month11Count,
0 as Month12Count, DepartmentName,ActivityDescription
from reports.WorkOrders
WHERE Month(BeginDate) = Month(@rptDate) + 1 and Year(BeginDate) = Year(DateAdd(month,1,@rptDate))
Group By DepartmentName, ActivityDescription
UNION
Select 0 As Month1Count, 0 As Month2Count, Count(*) as Month3Count,
0 as Month4Count, 0 as Month5Count, 0 as Month6Count, 0 as Month7Count,
0 as Month8Count, 0 as Month9COunt, 0 as Month10Count, 0 as Month11Count,
0 as Month12Count, DepartmentName, ActivityDescription
from reports.WorkOrders
WHERE Month(BeginDate) = Month(@rptDate) + 2 and Year(BeginDate) = Year(DateAdd(month,2,@rptDate))
Group By DepartmentName, ActivityDescription
見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple- sql-query – Strawberry
提供的代碼將爲您提供(最多)每個部門/活動的三行數據,分別具有第1,2和3個月的行數以及其他月份的零。如果這就是你想要的,我可以做不同的事情。但是我猜測這裏有一個包裝器,它爲每個部門和活動增加了一個月的總和(並且還有9個子查詢來覆蓋今年剩餘時間。請讓我們知道你需要 –
HI Steve,是的,你是對的,還有9個子查詢可以獲得今年餘下的時間,是的,每個部門有一個包裝將每月的數據彙總成一行。 ,但它似乎很麻煩,並希望可能有一個更簡潔的方式來完成相同的事情。 –