如何在结果集中使用 2 个分组列进行 PIVOT?
Posted
技术标签:
【中文标题】如何在结果集中使用 2 个分组列进行 PIVOT?【英文标题】:How to PIVOT with 2 grouping columns in the result set? 【发布时间】:2020-12-09 05:24:54 【问题描述】:我有一个查询输出以下内容:
ApptDate Truck_ID Item Qty
'8-19-20' TruckA ItemA 100
'8-19-20' TruckB ItemA 200
'8-20-20' TruckC ItemB 300
'8-20-20' TruckD ItemB 400
...
我需要 PIVOT 以便它返回:
Item Truck_ID Day1 Day2 ... Day14
ItemA TruckA 100 0 0
ItemA TruckB 200 0 0
ItemB TruckC 0 300 0
ItemB TruckD 0 400 0
我试过了,但是报错了:
消息 8114,第 16 级,状态 1,第 413 行 将数据类型 nvarchar 转换为日期时间时出错。 消息 473,第 16 级,状态 1,第 413 行 PIVOT 运算符中提供了不正确的值“Day1”。
select
item, truck_id, Day1, Day2, Day3, Day4, Day5, Day6, Day7, Day8, Day9, Day10, Day11, Day12, Day13, Day14
from(
select
ds.ApptDate
, c.truck_id
, c.item
, sum(c.qty) qty
from
maintable c with(nolock)
inner join secondtable ds with(nolock) on c.truck_id = ds.truckid and ds.type = 'O'
where
ds.apptdate between cast(getdate() as date) and dateadd(day, 14, cast(getdate() as date))
and coalesce(ds.CancelTruck, 0) <> 1
and ds.Status <> '5'
group by
c.truck_id
, c.item
, ds.ApptDate
) sourcetable
pivot
(
sum(qty)
for apptdate in ([Day1], [Day2], [Day3], [Day4], [Day5], [Day6], [Day7], [Day8], [Day9], [Day10], [Day11], [Day12], [Day13], [Day14])
) as pivottable
【问题讨论】:
【参考方案1】:由于您期望列数固定,我们不一定需要动态 SQL。一种选择使用条件聚合......以及大量重复输入:
select
item,
truck_id,
sum(case when appt_date = cast(getdate() as date) then qty else 0 end) day0,
sum(case when appt_date = dateadd(day, -1 , cast(getdate() as date)) then qty else 0 end) day1,
sum(case when appt_date = dateadd(day, -2 , cast(getdate() as date)) then qty else 0 end) day2,
...
sum(case when appt_date = dateadd(day, -14, cast(getdate() as date)) then qty else 0 end) day14
from ( -- your current query here --) t
group by item, truck_id
【讨论】:
大声笑我希望使用 PIVOT 找到一个奇特的解决方案。不过还是谢谢!!【参考方案2】:这种方法在最小日期和 AppDate 上使用 datediff。
;with
min_dt_cte(min_dt) as (select min(cast(AppDate as date)) from MyTable),
pvt_dt_cte(ApptDate, Truck_ID, Item, Qty, DayNum) as (
select t.*, datediff(d, mdc.min_dt, cast(AppDate as date))
from min_dt_cte mdc
cross join
MyTable t)
select
pdc.Item, pdc.Truck_ID,
iif(pdc.DayNum=1, Qty, 0) Day1,
iif(pdc.DayNum=2, Qty, 0) Day2,
...
iif(pdc.DayNum=14, Qty, 0) Day14
from
pvt_dt_cte pdc;
【讨论】:
以上是关于如何在结果集中使用 2 个分组列进行 PIVOT?的主要内容,如果未能解决你的问题,请参考以下文章