gpt4 book ai didi

sql - 根据组顺序选择新列

转载 作者:行者123 更新时间:2023-12-02 02:52:40 25 4
gpt4 key购买 nike

我在这个网站上遇到了很多问题,但无法找到解决方案。我有一张 table :

Date    GroupID CHANNEL24/02/2015  1   A26/02/2015  1   B27/02/2015  1   C21/03/2015  2   D20/02/2015  3   E25/02/2015  3   D28/02/2015  4   C04/03/2015  5   B05/03/2015  5   E10/03/2015  5   D11/03/2015  5   A14/03/2015  5   C23/03/2015  5   F28/03/2015  6   E

channel 仅限于“A”、“B”、“C”、“D”、“E”、“F”。其中有很多行具有不同的 GROUPID。

我需要得到这张表:

Date    GroupID Channel isFirst isLast  Channelsingroup Daysbeforelast24/02/2015  1       A   TRUE    FALSE   3                   326/02/2015  1       B   FALSE   FALSE   3                   127/02/2015  1       C   FALSE   TRUE    3                   021/03/2015  2       D   TRUE    TRUE    1                   020/02/2015  3       E   TRUE    FALSE   2                   525/02/2015  3       D   FALSE   FALSE   2                   028/02/2015  4       C   TRUE    TRUE    1                   004/03/2015  5       B   TRUE    FALSE   6                   1905/03/2015  5       E   FALSE   FALSE   6                   1810/03/2015  5       D   FALSE   FALSE   6                   1311/03/2015  5       A   FALSE   FALSE   6                   1214/03/2015  5       C   FALSE   FALSE   6                   923/03/2015  5       F   FALSE   FALSE   6                   028/03/2015  6       E   TRUE    TRUE    1                   0

IsFirst = TRUE 当 Channel 是按时间排序且具有相同 ID 的行组中的第一个时;否则为 FALSE。

IsLast = TRUE 当 Channel 是按时间排序且具有相同 GroupID 的行组中的最后一个时;否则为 FALSE。

Channelsingroup - 同一组中的行数(具有相同的 GroupID)

Daysbeforelast - 组中最新行与当前行之间的日期差异(以天为单位)。

我无权创建或更新表,只能选择。

我希望以上数据有意义,如有任何问题请告诉我。

最佳答案

一种解决方案可能是使用窗口聚合函数:

select 
*,
case when date = MIN(date) over (partition by groupid order by groupid) then 'TRUE' else 'FALSE' end isFirst,
case when date = MAX(date) over (partition by groupid order by groupid) then 'TRUE' else 'FALSE' end isLast,
count(*) over (partition by groupid order by groupid) Channelsingroup,
datediff(day,date,MAX(date) over (partition by groupid order by groupid)) Daysbeforelast
from your_table

Sample SQL Fiddle

关于sql - 根据组顺序选择新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30433024/

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