有没有办法(最好在不使用游标的情况下)计算同一用户在过去1小时内进行的交易次数。
这意味着该表
CREATE TABLE #TR (PK INT, TR_DATE DATETIME, USER_PK INT)
INSERT INTO #TR VALUES (1,'2018-07-31 06:02:00.000',10)
INSERT INTO #TR VALUES (2,'2018-07-31 06:36:00.000',10)
INSERT INTO #TR VALUES (3,'2018-07-31 06:55:00.000',10)
INSERT INTO #TR VALUES (4,'2018-07-31 07:10:00.000',10)
INSERT INTO #TR VALUES (5,'2018-07-31 09:05:00.000',10)
INSERT INTO #TR VALUES (6,'2018-07-31 06:05:00.000',11)
INSERT INTO #TR VALUES (7,'2018-07-31 06:55:00.000',11)
INSERT INTO #TR VALUES (8,'2018-07-31 07:10:00.000',11)
INSERT INTO #TR VALUES (9,'2018-07-31 06:12:00.000',12)
结果应为:
解决方案可能是这样的:COUNT(*)OVER(由USER_PK分配或按TR_DATE在((WHERE DATEADD(HH,-1,PRECENDING.TR_DATE)> CURRENT ROW.TR_DATE)和当前行...之间行)但是我知道ROWS BETWEEN不能那样使用...
答案 0 :(得分:0)
我猜是基于语法的SQL Server。在SQL Server中,您可以使用apply
:
select t.*, tr2.result
from #tr tr outer apply
(select count(*) as result
from #tr tr2
where tr2.user_id = tr.user_id and
tr2.tr_date > dateadd(hour, -1, tr.date) and
tr2.tr_date <= tr.tr_date
) tr2;
答案 1 :(得分:0)
SELECT USER_PK, COUNT(*) AS TransactionCount
FROM #TR
WHERE DATEDIFF(MINUTE, TR_DATE, GETDATE()) <= 60
AND DATEDIFF(MINUTE, TR_DATE, GETDATE()) >= 0
GROUP BY USER_PK
您可以根据需要更改GETDATE()
,但它们需要具有相同的值