sql - 查看sql中按时间间隔分组的二次请求分布
问题描述
我有下表:
RequestId,Type, Date, ParentRequestId
1 1 2020-10-15 null
2 2 2020-10-19 1
3 1 2020-10-20 null
4 2 2020-11-15 3
对于此示例,我对请求类型 1 和 2 感兴趣,以使示例更简单。我的任务是查询一个大数据库,并根据与父事务的日期差异查看二级事务的分布。所以结果看起来像:
Interval,Percentage
0-7 days,50 %
8-15 days,0 %
16-50 days, 50 %
因此,对于预期结果的第一行,我们有 id 2 的请求,对于预期结果的第三行,我们有 id 4 的请求,因为日期差异适合这个间隔。
如何做到这一点?
我正在使用 sql server 2014。
解决方案
我们希望看到您的尝试,但从外观上看,您似乎需要将此表视为 2 个表并执行基本的 GROUP BY,但通过在 CASE 语句上进行分组来使其看起来很有趣。
WITH dateDiffs as (
/* perform our date calculations first, to get that out of the way */
SELECT
DATEDIFF(Day, parent.[Date], child.[Date]) as daysDiff,
1 as rowsFound
FROM (SELECT RequestID, [Date] FROM myTable WHERE Type = 1) parent
INNER JOIN (SELECT ParentRequestID, [Date] FROM myTable WHERE Type = 2) child
ON parent.requestID = child.parentRequestID
)
/* Now group and aggregate and enjoy your maths! */
SELECT
case when daysDiff between 0 and 7 then '0-7'
when daysDiff between 8 and 15 then '8-15'
when daysDiff between 16 and 50 THEN '16-50'
else '50+'
end as myInterval,
sum(rowsFound) as totalFound,
(select sum(rowsFound) from dateDiffs) as totalRows,
1.0 * sum(rowsFound) / (select sum(rowsFound) from dateDiffs) * 100.00 as percentFound
FROM dateDiffs
GROUP BY
case when daysDiff between 0 and 7 then '0-7'
when daysDiff between 8 and 15 then '8-15'
when daysDiff between 16 and 50 THEN '16-50'
else '50+'
end;
推荐阅读
- java - 堆栈映射与异常处理程序中的不匹配 - Spring Boot
- python - 使用 python authlib 解析 id_token 时出现 UnsupportedAlgorithmError
- python - Python Mysql - 无法在 mysql 数据库中插入随机数据
- regression - 边距与 lincom/nlcom(在 Stata 中)有何不同?
- javascript - Firebase 查询未使用 Javascript 将变量提交到 firebase 数据库
- asp.net - 格式化日期时出现问题
- sql - 查找唯一子集
- c# - Azure Functions QueueTrigger 从不触发
- docker - 难以运行简单的 Pod 命令
- python - 具有 403 个输出的 ANN 预测 CAD 网格