Sql 一列的自定义聚合

Sql 一列的自定义聚合,sql,postgresql,Sql,Postgresql,如下图所示的表格1 +------+-----+------+----------+-----------+ | city | day | hour | car_name | car_count | +------+-----+------+----------+-----------+ | 1 | 12 | 00 | corolla | 8 | | 1 | 12 | 00 | city | 9 | | 1 | 13 |

如下图所示的表格1

+------+-----+------+----------+-----------+
| city | day | hour | car_name | car_count |
+------+-----+------+----------+-----------+
|    1 |  12 |   00 | corolla  |         8 |
|    1 |  12 |   00 | city     |         9 |
|    1 |  13 |   00 | corolla  |        17 |
|    1 |  13 |   00 | city     |         2 |
|    1 |  14 |   00 | corolla  |         3 |
+------+-----+------+----------+-----------+
对于每个城市、天、小时,需要找出car_count中car_Name corolla和city的差异计数,不包括两者或其中一方都不存在的情况。count_diff本质上是[花冠数-城市数]

预期产量


你可以试试这个。

假设sam ehour不能有几张花冠?。是的,每个城市、每天、每小时、每辆车的名字不能超过一张
+------+-----+------+-----------+
| city | day | hour | count_diff|
+------+-----+------+-----------+
|    1 |  12 |   00 | -1        | 
|    1 |  13 |   00 | 15        | 
+------+-----+------+-----------+
t=# with a as (
  select
  *
  , count(1) over a
  , car_count - lead(car_count) over a count_diff
  from table1
  window a as (partition by city,day,hour)
)
select city,day,hour,count_diff
from a
where count >1 and count_diff is not null;
 city | day |  hour  | count_diff
------+-----+--------+------------
    1 |  12 |    00  |         -1
    1 |  13 |    00  |         15
(2 rows)

Time: 0.411 ms
with data as 
(select city, day, hour , 
    sum(case when  car_name = 'corolla' then car_count else 0 end) corolla_count, 
    sum(case when  car_name = 'city' then car_count else 0 end) as city_count
 group by city, day, hour
) 
select city, day, hour, corolla_count - city_count from data 
where corrolla_count > 0 and city_count > 0