我有一个SQL查询,用于显示在指定日期范围内按天创建的工作订单数量。当我查询单个日期范围时,例如3/1/2016到2016年3月31日,它很有效。
SELECT DATEADD(dd, DATEDIFF(dd, 0, dateCreated), 0) the_date,
COUNT(*) work_order_count
FROM WorkOrder
where active = 1 and
dateCreated >= '3/1/2016' and
dateCreated <= '3/31/2016 23:59:59'
GROUP BY DATEADD(dd, DATEDIFF(dd, 0, dateCreated), 0)
order by 1;
我想进一步采取相同的查询,以便我可以查询相同的数据,但显示多个日期范围的结果。我的具体目的是为前一年的比较并排显示数据。理想情况下,我想显示在2014年,2015年和2016年为3 / 1-3 / 31创建的工作订单数量,但都在同一视图/结果中。
这可能吗?我已经查看了连接,但它们似乎是在你使用不同的表时,而不是同一个表。
答案 0 :(得分:1)
只需使用条件聚合(或支点):
SELECT CAST(dateCreated as DATE) as the_date,
SUM(CASE WHEN YEAR(dateCreated) = 2014 THEN 1 ELSE 0 END) as cnt_2014,
SUM(CASE WHEN YEAR(dateCreated) = 2015 THEN 1 ELSE 0 END) as cnt_2015,
SUM(CASE WHEN YEAR(dateCreated) = 2016 THEN 1 ELSE 0 END) as cnt_2016
FROM WorkOrder
WHERE active = 1 and
MONTH(dateCreated) = 3 and
YEAR(dateCreated) in (2014, 2015, 2016)
GROUP BY CAST(dateCreated as DATE)
ORDER BY the_date;
答案 1 :(得分:0)
使用数据透视表:
;with cte1 as (
select dateCreated, datepart(year, dateCreated) as Y
from WorkOrder
where datepart(month, dateCreated) = 3 and datepart(day, dateCreated) between 5 and 25
)
SELECT *
FROM cte1
PIVOT
(
count(dateCreated)
FOR Y in ([2014], [2015], [2016])
) as pv
答案 2 :(得分:0)
如下:
$http
答案 3 :(得分:0)
SELECT datepart(dd, 'yyyy'), datepart(dd, 'MM'), datepart(dd, 'dd'),
COUNT(*) work_order_count
FROM WorkOrder
where active = 1
and dateCreated >= '3/1/2016'
and dateCreated < '4/1/2020'
GROUP BY datepart(dd, 'yyyy'), datepart(dd, 'MM'), datepart(dd, 'dd')
order by datepart(dd, 'yyyy'), datepart(dd, 'MM'), datepart(dd, 'dd');