我正在尝试在 SQL 中创建一个表,显示每个用户每次存款之间的小时数差异,例如(第一次存款与第二次存款、第二次存款与第三次存款、第三次存款与第四次存款等...)
这是原始表格:
with q1 as (SELECT
[UserId],
[DepositAttemptDate],
[AmountSystem]
FROM [dbo].[v_DepositAttempts_Marketing]
WHERE [DepositAttemptDate] >= '2024-01-01' AND [Status] IN ('Completed', 'Complete', 'Confirmed') AND [DepositType]=''
ORDER BY [UserId] ASC, [DepositAttemptDate] DESC)
用户 | 存款日期 | 价值 |
---|---|---|
83815-fa85-466b-aaa7-00029c5 | 2024-10-30 12:42:58.793 | 8.698677800974 |
62ac8-5d7f-464a-993c-00039b1 | 2024-02-28 20:38:59.883 | 253.390000000000 |
62ac8-5d7f-464a-993c-00039b1 | 2024-02-28 19:09:26.323 | 253.390000000000 |
62ac8-5d7f-464a-993c-00039b1 | 2024-02-28 18:15:13.223 | 253.390000000000 |
62ac8-5d7f-464a-993c-00039b1 | 2024-02-28 17:54:17.340 | 253.390000000000 |
62ac8-5d7f-464a-993c-00039b1 | 2024-02-06 19:43:12.757 | 115.140000000000 |
62ac8-5d7f-464a-993c-00039b1 | 2024-01-30 13:36:56.937 | 253.390000000000 |
62ac8-5d7f-464a-993c-00039b1 | 2024-01-09 14:20:03.440 | 405.040000000000 |
17f62-01c7-4a9c-ba28-0003b7f | 2024-05-15 18:50:18.350 | 51.500000000000 |
17f62-01c7-4a9c-ba28-0003b7f | 2024-03-21 22:59:57.217 | 51.500000000000 |
17f62-01c7-4a9c-ba28-0003b7f | 2024-01-21 13:24:44.393 | 51.500000000000 |
17f62-01c7-4a9c-ba28-0003b7f | 2024-01-03 20:13:14.167 | 51.500000000000 |
76763-384a-46cb-9a08-0004393 | 2024-09-06 18:51:29.677 | 103.000000000000 |
76763-384a-46cb-9a08-0004393 | 2024-09-05 00:01:44.587 | 51.500000000000 |
76763-384a-46cb-9a08-0004393 | 2024-08-25 03:42:08.290 | 103.000000000000 |
假设这是 SQL Server 并猜测您希望结果有多准确(因为您也没有指定),那么您可以尝试其中之一
DATEDIFF(HOUR, LAG(DepositAttemptDate, 1, DepositAttemptDate) OVER(PARTITION BY UserId ORDER BY DepositAttemptDate), DepositAttemptDate) AS FullHours
或
DATEDIFF(MINUTE, LAG(DepositAttemptDate, 1, DepositAttemptDate) OVER(PARTITION BY UserId ORDER BY DepositAttemptDate), DepositAttemptDate)/60.0 AS DecimalHours
第一个将为您提供完整的小时数,第二个将为您提供十进制表示形式,因此例如,将返回 3 小时 6 分钟
3.1
在这两个示例中,我们都使用
LAG
来获取之前的日期时间。如果没有找到以前的记录(每个 UsersId 的第一条记录),我们将返回当前记录的 DepositAttemptDate,因此在这些情况下 DATEDIFF
将返回 0。