2017-03-03 77 views
1

與表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),用於每個站的汽車的移動,不同汽車用make hondanon-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'

回答

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 
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