我有一个表格,每个点都有一个时间属性(“小时”列),位于不同的沙砾方块中(由“gridid”列标记)。
对于每个正方形,我想获得按小时分组的点数,从而得到一个包含 24 列 + 与现有网格 ID 一样多的行的表。
到目前为止,我用 24 个左连接(下图)做到了这一点。有没有办法用一个简单的循环来简化查询?
SELECT * from (select gridid, count(id) as "00" from points where hour = 0 GROUP BY gridid ORDER BY "00" DESC)t00
left join
(select gridid, count(id) as "01" from points where hour = 1 GROUP BY gridid)t01
on t01.gridid = t00.gridid
left join
(select gridid, count(id) as "02" from points where hour = 2 GROUP BY gridid)t02
on t02.gridid = t00.gridid
...
left join
(select gridid, count(id) as "24" from points where hour = 24 GROUP BY gridid)t02
on t02.gridid = t24.gridid