我有以下架构:
表T
|ITEM_ID| |USER_ID| | DUE_DATE |
1 1 2018-01-2
1 1 2018-01-2
1 1 2018-01-3
1 2 2018-01-2
2 1 2018-01-2
2 2 2018-01-2
我想要的是获取一个独特用户在一周内执行的操作计数。
这是我正在使用的选择查询,但它没有关注唯一用户的事实。
select ITEM_ID,
sum(case when cast(due_date as date) = cast(getdate() as date) then 1 else 0 end) as today,
sum(case when cast(due_date as date) >= cast(getdate() - 7 as date) then 1 else 0 end) as week,
sum(case when cast(due_date as date) >= dateadd(month, -1, cast(getdate() as date)) then 1 else 0 end) as month
from t
group by ITEM_ID;
如何在特定日期(一周)内选择唯一身份用户执行的操作计数。
例如:我们假设今天是2018-01-2
所以预期的结果应该是:
ITEM_ID, COUNT_TODAY, COUNT_TOMORROW
1 2 1
2 1 1
我需要的是当天执行该特定项目类型的交易的唯一用户。
在上面的例子中,id为1的用户在 2018-01-2上执行 类型1 的交易2次。所以它应该算作1而不是2.
我怎样才能做到这一点?
答案 0 :(得分:0)
这就是你想要的。
select USER_ID, ITEM_ID,
sum(case when cast(due_date as date) = cast(getdate() as date) then 1 else 0 end) as today,
sum(case when cast(due_date as date) >= cast(getdate() - 7 as date) then 1 else 0 end) as week,
sum(case when cast(due_date as date) >= dateadd(month, -1, cast(getdate() as date)) then 1 else 0 end) as month
from t
group by USER_ID, ITEM_ID;