使用下面的表table1
跟踪租车站的汽车移动
+---------+---------+----------+--------+------+-------+-------+--------+
| station | make | model | start | end | kms | time | regno |
+---------+---------+----------+--------+------+-------+-------+--------+
| 1111 | toyota | camry | ca | mh | 1200 | 12 | 2222 |
| 1111 | toyota | camry | ca | mg | 1300 | 14 | 2233 |
| 1111 | honda | accord | ab | mx | 1400 | 12 | 2255 |
| 1111 | honda | accord | ab | mx | 1400 | 12 | 2255 |
| 1122 | toyota | corolla | ab | mg | 800 | 8 | 2244 |
| 1133 | honda | accord | ab | mx | 900 | 7 | 2255 |
| 1133 | honda | accord | ab | mx | 900 | 7 | 2277 |
+---------+---------+----------+--------+------+-------+-------+--------+
需要为每个电台查找不同的汽车(regno
),与honda
和non-honda
不同的汽车,如下面的预期输出
+---------+----------------------+--------------------------+------------------------------+
| station | distinct_cars_count | make_honda_distinct_cnt | make_non_honda_distinct_cnt |
+---------+----------------------+--------------------------+------------------------------+
| 1111 | 3 | 1 | 2 |
| 1122 | 1 | 0 | 1 |
| 1133 | 2 | 2 | 0 |
+---------+----------------------+--------------------------+------------------------------+
我可以在下面找到不同的汽车
select
count(distinct regno) as distinct_cars_count
from table1
group by station
我需要帮助找到make_honda_distinct_cnt
这是与make = 'honda'
和make_non_honda_distinct_cnt
不同的汽车,这些汽车将是make <> 'honda'
答案 0 :(得分:4)
您可以使用filter()
子句使用条件聚合:
select count(distinct regno) as distinct_cars_count ,
count(distinct regno) filter (where make = 'honda') as make_honda_distinct_cnt,
count(distinct regno) filter (where make <> 'honda') as make_non_honda_distinct_cnt
from table1
group by station
答案 1 :(得分:1)
您可以在计数中使用case
语句:
select station,
count(distinct regno) as distinct_cars_count,
count(distinct case when make = 'honda' then regno end) as make_honda_distinct_cnt,
count(distinct case when make <> 'honda' then regno end) as make_non_honda_distinct_cnt,
from table1
group by station