sqlite-使用cte划分查询

1cosmwyk  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(328)

给那些sqlMaven提个简单的问题。我觉得自己有点傻,因为我觉得自己已经接近解决问题的方法了,但却没能做到。
如果我有这两个表,如何使用前一个表来划分第二个表的列?

WITH month_usage AS 
(SELECT strftime('%m', starttime) AS month, SUM(slots) AS total
 FROM Bookings
 GROUP BY month)

SELECT strftime('%m', b.starttime) AS month, f.name, SUM(slots) AS usage
FROM Bookings as b 
LEFT JOIN Facilities as f
ON b.facid = f.facid
GROUP BY name, month
ORDER BY month

第一个计算每个月的总数

第二个是我想用usage列除以每个月的总数得到的百分比

当我使用month作为id连接两个表时,会把内容弄乱,有什么建议吗?

vsikbqxv

vsikbqxv1#

我想用usage列除以每个月的总数得到百分比
只需使用窗口功能:

SELECT 
    strftime('%m', b.starttime) AS month, 
    f.name, 
    SUM(slots) AS usage
    1.0 * SUM(slots) AS usage 
        / SUM(SUM(slots)) OVER(PARTITION BY strftime('%m', b.starttime)) ratio
FROM Bookings as b 
LEFT JOIN Facilities as f
ON b.facid = f.facid
GROUP BY name, month
ORDER BY month

相关问题