sql - 在 PostgreSQL 中生成百分比报告的复杂 SQL 查询
问题描述
我有这张桌子。
列名 | 数据类型 |
---|---|
ID | uuid |
起源 | uuid |
类型 | varchar(31) |
日期 | 时间戳 |
示例记录:
ID | 起源 | 类型 | 日期 |
---|---|---|---|
1 | 1111 | 一个 | 2021-11-09 10:01:31.001 |
2 | 1111 | 一个 | 2021-11-08 03:02:22.020 |
3 | 1111 | 乙 | 2021-10-01 11:03:13.003 |
4 | 2222 | 一个 | 2021-11-07 13:04:54.040 |
5 | 3333 | 乙 | 2021-11-09 20:05:45.005 |
6 | 3333 | 乙 | 2021-11-08 21:06:36.060 |
7 | 3333 | 乙 | 2021-11-08 00:07:27.700 |
我想做一个 SQL 查询,生成一个报告,显示过去 7 天(列)origin
中每个type
或两者都有的 s 的百分比。date
有几条相同的记录origin
。
期望的示例结果:
PercentageOfOriginThatHasTypeAInLast7Days | PercentageOfOriginThatHasTypeBInLast7Days | PercentageOfOriginThatHasBothTypeInLast7Days |
---|---|---|
66.66 | 33.33 | 0 |
我怎么能那样做?
我正在使用 PostgreSQL 11.x
解决方案
您可以使用cte
:
with cte as (
select r.origin, r.type, count(*) c from records r where r.date >= now() - interval '7 day' group by r.origin, r.type
),
cte1 as (
select c.origin, count(distinct c.type) c1 from cte c group by c.origin
)
select sum(case when c.type = 'A' then 1 end)/cast((select count(*) from cte) as float),
sum(case when c.type = 'B' then 1 end)/cast((select count(*) from cte) as float),
(select count(*) from cte1 c1 where c1.c1 = (select count(distinct c3.type) from records c3))/((select count(*) from cte) as float)
from cte c
推荐阅读
- android-studio - 当我运行我的项目时,为什么会出现这个错误?
- typescript - 在 Angular 6 中集成 Stripe 支付网关时面临“需要卡”错误
- hdfs - HA namenode config的hdfs上的Flink检查点
- node.js - 这是在 docker 容器内的 node.js 和云问题上运行的通用 expressjs
- javascript - 在reactjs中按字母顺序排列标题
- selenium - AutomationTest 类型中的方法 EnterText(WebElement, String) 指的是缺少的类型 WebElement
- html - CSS Grid未在指定的网格列中显示项目
- amcharts - 为什么 am4charts.XYChart 忽略日期轴上某些值的日期格式?
- python - 为什么在处理数据框时缺少索引方法?
- php - 如何在php中调用当前文件?