SQL小提琴:http://sqlfiddle.com/#!18/b871d/23
我有一个查询
-- DECLARE @Startdate datetime,
-- @Enddate datetime
WITH Table1 AS
(
select
ID,
ItemNumber,
CAST(year(DateSold) AS VARCHAR(4)) + ' ' + DATENAME(m, DateSold) AS
[DateSold2],
Qty
-- Price,
-- Cost
from ItemOrder
)
select * from Table1
pivot (sum(Qty) for[DateSold2] IN ([2018 August], [2018 July], [2018 June]))
as d
结果:
| ID | ItemNumber | DateSold | 2018 August | 2018 July | 2018 June |
|----|------------|----------------------|-------------|-----------|-----------|
| 1 | 145 | 2018-08-06T00:00:00Z | 5 | (null) | (null) |
| 2 | 145 | 2018-07-04T00:00:00Z | (null) | 5 | (null) |
| 3 | 145 | 2018-06-06T00:00:00Z | (null) | (null) | 5 |
我该如何动态地进行调整?例如用户可以输入任何日期范围,这需要在这几个月内进行调整。
此行
pivot (sum(Qty) for[DateSold2] IN ([2018 August], [2018 July], [2018 June]))
我该如何创建一个不知道几个月的查询?