gpt4 book ai didi

sql-server - T-SQL 将计数器添加到分组数据

转载 作者:行者123 更新时间:2023-12-04 02:05:49 27 4
gpt4 key购买 nike

我正在尝试生成一个查询,该查询显示为每组数据集递增(计数)的列。结果的总体顺序无关紧要,除了出现必须按日期计数(最旧 = 1)并且应该为每组分组数据重置。这是一个示例表 ProductInteractions。

+---------+------------+----------------+------------+
| User ID | Product ID | Date Purchased | Occurrence |
+---------+------------+----------------+------------+
| user15 | b1290 | 1/1/2012 | 1 |
| user15 | b1290 | 1/15/2013 | 2 |
| user15 | b1290 | 3/15/2019 | 3 |
| user15 | a7983 | 7/22/2017 | 1 |
| user2 | a7983 | 12/3/2015 | 1 |
| user2 | a7983 | 5/6/2016 | 2 |
| user3 | a7983 | 3/24/2017 | 1 |
+---------+------------+----------------+------------+

原始数据:

+---------+------------+-----------+
| User ID | Product ID | Date |
+---------+------------+-----------+
| user15 | b1290 | 1/1/2012 |
| user2 | a7983 | 5/6/2016 |
| user15 | b1290 | 3/15/2019 |
| user15 | a7983 | 7/22/2017 |
| user2 | a7983 | 12/3/2015 |
| user15 | b1290 | 1/15/2013 |
| user3 | a7983 | 3/24/2017 |
+---------+------------+-----------+

请注意,在上面的示例中,user15 和产品 b1290 有 3 次交互。重要的是,第一次出现与初始交互日期相关联,后续交互按递增日期计数。

我相信查询的基本格式会是:

    SELECT [User ID],
[Product ID],
[Date Purchased]
-- Something here utilizing IDENTITY, maybe?
FROM ProductInteractions
GROUP BY [User ID],
[Product ID];


最佳答案

使用 ROW_NUMBER()

下面是测试/验证脚本的代码:用您自己的表替换 ProductInteractions

declare @ProductInteractions as table([User ID] varchar(50),[Product ID] varchar(50),[Date] datetime)
insert into @ProductInteractions values
('user15' , 'b1290' , '1/1/2012' ),
('user2' , 'a7983' , '5/6/2016' ),
('user15' , 'b1290' , '3/15/2019' ),
('user15' , 'a7983' , '7/22/2017' ),
('user2' , 'a7983' , '12/3/2015' ),
('user15' , 'b1290' , '1/15/2013' ),
('user3' , 'a7983' , '3/24/2017' )

select [User ID],[Product ID],[Date],
row_number() over(partition by [User ID],[Product ID] order by [date]) [occurence]
from @ProductInteractions order by [Product ID] desc

enter image description here

关于sql-server - T-SQL 将计数器添加到分组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55479890/

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