【发布时间】:2023-04-09 02:53:02
【问题描述】:
我想计算 (pid = pid_raw) 在 pid_raw 总数中的百分比,其中 date_raw 是日期前 31 天。
我知道我可以通过内部联接部分完成,但因为我想获得百分比,因此无论匹配如何都需要 pid_raw 的总数,因此该子查询不能成为内部联接的一部分。如何编写子查询以获得不受内部连接影响但符合 where 子句的 pid_raw 总数?
table1
date pid
2015-06-01 223
2015-06-01 333
2015-05-01 124
2015-05-01 543
table2
date_raw pid_raw
2015-05-30 223
2015-05-15 111
2015-05-03 333
2015-05-02 242
2015-05-05 300
2015-04-10 124
2015-04-15 543
2015-04-09 511
Example output
date pid_percentage
2015-06-01 0.40 <-------(2/5)
2015-05-01 0.67 <------(2/3)
我的 sudo 代码:
select count(a.pid)/(select count(b.pid_raw) from b) AS pid_percentage, a.date from
table1 a join table2 b
ON a.pid = b.pid_raw
Where a.date - b.date_raw <=31 and a.date - b.date_raw > 0
group by a.date
order by YEAR(a.date),Month(a.date);
【问题讨论】: