我在这个网站上遇到了很多问题,但无法找到解决方案。 我有一张 table :
Date GroupID CHANNEL 24/02/2015 1 A 26/02/2015 1 B 27/02/2015 1 C 21/03/2015 2 D 20/02/2015 3 E 25/02/2015 3 D 28/02/2015 4 C 04/03/2015 5 B 05/03/2015 5 E 10/03/2015 5 D 11/03/2015 5 A 14/03/2015 5 C 23/03/2015 5 F 28/03/2015 6 E
channel 仅限于“A”、“B”、“C”、“D”、“E”、“F”。其中有很多行具有不同的 GROUPID。
我需要得到这张表:
Date GroupID Channel isFirst isLast Channelsingroup Daysbeforelast 24/02/2015 1 A TRUE FALSE 3 3 26/02/2015 1 B FALSE FALSE 3 1 27/02/2015 1 C FALSE TRUE 3 0 21/03/2015 2 D TRUE TRUE 1 0 20/02/2015 3 E TRUE FALSE 2 5 25/02/2015 3 D FALSE FALSE 2 0 28/02/2015 4 C TRUE TRUE 1 0 04/03/2015 5 B TRUE FALSE 6 19 05/03/2015 5 E FALSE FALSE 6 18 10/03/2015 5 D FALSE FALSE 6 13 11/03/2015 5 A FALSE FALSE 6 12 14/03/2015 5 C FALSE FALSE 6 9 23/03/2015 5 F FALSE FALSE 6 0 28/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
关于sql - 根据组顺序选择新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30433024/