我需要一些查询的帮助,该查询将在一个输出上提供两年数据的结果。例如,仅仅比较单位;
查询:
select
year 1,count(*),
year 2, count(*)
From db
WHERE year1 >= DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))
AND year1 <= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 12, 0)
AND
year2 >= DATEADD(yy,0,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))
AND year2 <= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) , 0)
结果视觉:
2016 Units 2017 units
3000 1200
答案 0 :(得分:2)
使用case语句+ sum aggregat,假设yy
是你的日期列:
select
sum(case when '2016' = Year(yy) then 1 else 0 end) as "2016 units",
sum(case when '2017' = Year(yy) then 1 else 0 end) as "2017 units"
From table
会产生一行:
2016 Units 2017 units
3000 1200
另一个演示文稿(多行):
select
Year(yy) as year,
count as units
From table
where Year(yy) in (2016,2017)
group by
Year(yy)
将产生:
year Units
2016 3000
2017 1200