gpt4 book ai didi

sql - 在 T-SQL 中旋转两列

转载 作者:行者123 更新时间:2023-12-04 20:56:14 27 4
gpt4 key购买 nike

首先 - 我已经看了两天示例并尝试应用它们但没有成功。我不了解 Pivot 的工作机制,希望得到一些帮助。

我有一个数据集,每个客户有多行 - 每次购买一行。我想为每个客户获取一行 - 最多 6 次购买以及每次的购买日期。

老实说,我什至不知道这是否可能...因为购买日期 [PDate] 可能相差很大。 ?

这是我的起始数据集的 SQL:

DECLARE @Test AS TABLE 
(
Location VARCHAR(20),
Mgr VARCHAR(30),
CId VARCHAR(20),
CName VARCHAR(100),
BDate DATE,
Age Int,
Item Varchar(15),
PDate Date
)

Insert Into @Test
(Location, Mgr, CId, CName, BDate, Age, Item, PDate)
Values
('A','Bob','1','Bill Jones','1967-04-27', 50,'Hammer','2017-04-05'),
('A','Bob','1','Bill Jones','1967-04-27', 50,'Nails','2017-03-17'),
('A','Bob','1','Bill Jones','1967-04-27', 50,'Screws','2017-02-15'),
('A','Bob','1','Bill Jones','1967-04-27', 50,'Nails','2017-01-26'),
('A','Bob','1','Bill Jones','1967-04-27', 50,'Screws','2016-12-20'),
('A','Bob','1','Bill Jones','1967-04-27', 50,'Nails','2016-11-03'),
('B','Dan','15','Sharon Jones','1969-04-27', 48,'Nails','2017-04-05'),
('B','Dan','15','Sharon Jones','1969-04-27', 48,'Nails','2017-03-07'),
('B','Dan','15','Sharon Jones','1969-04-27', 48,'Screws','2017-02-18')
Select * From @Test

我需要看这个:

A Bob 1  Bill Jones   1967-04-27 50 Hammer 2017-04-05 Nails 2017-03-17 .... 
B Dan 15 Sharon Jones 1969-04-27 48 Nails 2017-04-05 Nails 2017-03-07 ....

...本质上,每个 CId 一行:位置、经理、CId、CName、BDate、年龄、Item1、Date1、Item2、Date2、Item3、Date3... 最多购买 6 件商品。

提前致谢!

最佳答案

由于您不需要动态调整并在 6 时达到最大值,因此一个简单的条件聚合就可以了。

Select Location, Mgr, CId, CName, BDate, Age
,[Item1] = max(case when RN=1 then Item end)
,[Date1] = max(case when RN=1 then Pdate end)
,[Item2] = max(case when RN=2 then Item end)
,[Date2] = max(case when RN=2 then Pdate end)
,[Item3] = max(case when RN=3 then Item end)
,[Date3] = max(case when RN=3 then Pdate end)
,[Item4] = max(case when RN=4 then Item end)
,[Date4] = max(case when RN=4 then Pdate end)
,[Item5] = max(case when RN=5 then Item end)
,[Date5] = max(case when RN=5 then Pdate end)
,[Item6] = max(case when RN=6 then Item end)
,[Date6] = max(case when RN=6 then Pdate end)
From (
Select *
,RN = Row_Number() over (Partition By Location, Mgr, CId, CName, BDate, Age Order by Item,PDate)
From Test
) A
Group By Location, Mgr, CId, CName, BDate, Age

返回 enter image description here

As Requested - Some Commentary

这是一个简单的条件聚合,略有不同。扭曲是使用窗口函数 Row_Number() 的子查询。子查询生成以下内容:

enter image description here

注意最后一列 RN。您可能会看到它是按 Location、Mgr、CId、CName、BDate、Age 分区并按 Item,PDate

排序的增量 YET

一旦子查询被取消(使用 RN),我们就可以应用最终的聚合,它本质上是一个枢轴

窗口函数非常宝贵,值得您花时间熟悉它们,

关于sql - 在 T-SQL 中旋转两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43666695/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com