我有两个表来计算记录并按月显示计数。
我想在同一张桌子上显示两个计数,但我不确定如何将它们合并。
我只想添加" IM Count"列到第一个表,右边是" CR计数。"
下面是第一个表的代码。第二个表是类似的代码,但它从另一个表中绘制数据。我的主要问题是我没有表格之间匹配的列。 (“年”和“月”列在技术上匹配,但仅仅因为它们都是每月的计数。)
Use sm
select
year(planned_start) Year,
Case
When month(planned_start) = 1 then 'January'
When month(planned_start) = 2 then 'February'
When month(planned_start) = 3 then 'March'
When month(planned_start) = 4 then 'April'
When month(planned_start) = 5 then 'May'
When month(planned_start) = 6 then 'June'
When month(planned_start) = 7 then 'July'
When month(planned_start) = 8 then 'August'
When month(planned_start) = 9 then 'September'
When month(planned_start) = 10 then 'October'
When month(planned_start) = 11 then 'November'
When month(planned_start) = 12 then 'December'
end as Month,
count(*) 'CR Count'
from dbo.cm3rm1
where planned_start between dateadd(Year,-1,getdate()) and getdate()
and
category !='OAS Normal'
group by year(planned_start), month(planned_start)
order by year(planned_start), month(planned_start)
答案 0 :(得分:0)
嗯,对于"的想法" :
SELECT tmp_CR.Year,
Case
When tmp_CR.month = 1 then 'January'
When tmp_CR.month = 2 then 'February'
When tmp_CR.month = 3 then 'March'
When tmp_CR.month = 4 then 'April'
When tmp_CR.month = 5 then 'May'
When tmp_CR.month = 6 then 'June'
When tmp_CR.month = 7 then 'July'
When tmp_CR.month = 8 then 'August'
When tmp_CR.month = 9 then 'September'
When tmp_CR.month = 10 then 'October'
When tmp_CR.month = 11 then 'November'
When tmp_CR.month = 12 then 'December' end as month,
tmp_CR.CR_Count,
tmp_IM.IM_Count
FROM (
select
year(planned_start) Year,
month(planned_start) as Month,
count(*) as CR_Count
from dbo.TABLE_1
where planned_start between dateadd(Year,-1,getdate()) and getdate()
and
category !='OAS Normal'
group by year(planned_start), month(planned_start)
) tmp_CR
INNER JOIN (
select
year(planned_start) Year,
month(planned_start) as Month, as Month,
count(*) as IM_Count
from dbo.TABLE_2
where planned_start between dateadd(Year,-1,getdate()) and getdate()
and
category !='OAS Normal'
group by year(planned_start), month(planned_start)
) tmp_IM ON tmp_CR.year = tmp_IM.year and tmp_CR.month = tmp_IM.month
ORDER BY tmp_CR.Year, tmp_CR.month