根据组顺序选择新列

use*_*823 6 sql sql-server group-by sql-order-by

我在这个网站上经历了很多问题,但是无法找到解决方案.我有一张桌子:

__PRE__

频道限于'A','B','C','D','E','F'.它中有很多行有不同的GROUPID.

我需要得到这张桌子:

__PRE__

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

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

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

Daysbeforelast - 在该组中最新一行与当前行之间的天数.

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

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

jpw*_*jpw 4

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

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
Run Code Online (Sandbox Code Playgroud)

示例 SQL 小提琴