连续几天运行列中唯一字符串值的总数

时间:2018-11-02 15:22:58

标签: sql sql-server

我有一个设备登录的sql表,如下所示:

date,        username,      devicename
2018-09-05,  bricew,       brice-pc
2018-09-05,  bricew,       brice-laptop
2018-09-06,  bricew,       brice-laptop
2018-09-06,  bricew,       brice-ipad
2018-09-06,  johnm,        john-pc
2018-09-06,  bricew,       brice-laptop

如何每天获得每个用户名唯一设备的总运行量? 我想要的示例列看起来像这样:

running_total
1
2
2
3
1
3

1 个答案:

答案 0 :(得分:2)

SQL Server具有窗口功能。因此,看来您可以:

count(distinct)

A,对窗口函数的支持并不扩展到row_number()的这种用法。您可以使用子查询来执行此操作。一种方法使用select t.*, sum(case when seqnum = 1 then 1 else 0 end) over (partition by date, username) as running_total from (select t.*, row_number() over (partition by date, username, device_name order by (select null)) as seqnum from t ) t;

dense_rank()

另一种方法使用select t.*, max(seqnum) over (partition by date, username) as running_total from (select t.*, dense_rank() over (partition by date, username order by device_name) as seqnum from t ) t;

string