查找所有城市的计数

Find the counts for all cities

我有一个tableFiddle here

+------+------+------+---------+
| id_a | id_b | City | result  |
+------+------+------+---------+
| 101  | 101  | NY   | Ready   |
| 102  | 102  | TN   | Sold    |
| 103  |      | TN   | Missing |
| 104  | 104  | NY   | Ready   |
|      | 105  | NY   | Missing |
| 106  | 106  | TN   | Ready   |
| 107  | 107  | TN   | Sold    |
+------+------+------+---------+

我需要像

这样的输出
+------+-----+----------+---------+------------+
| City | CNT | No_Ready | No_sold | No_Missing |
+------+-----+----------+---------+------------+
| NY   | 3   | 2        | 0       | 1          |
| TN   | 4   | 1        | 2       | 1          |
+------+-----+----------+---------+------------+

逻辑只是计算每个城市的每个结果。现在我得到以下查询的结果

select 'NY' as City,sum(case when city='NY' then 1 else 0 end) as CNT,
            sum(case when city='NY' and result='Ready' then 1 else 0 end) as No_Ready,
            sum(case when city='NY' and result='Sold' then 1 else 0 end) as No_sold,
            sum(case when city='NY' and result='Missing' then 1 else 0 end) as No_Missing
from source
union all
select 'TN' as City,sum(case when city='TN' then 1 else 0 end) as CNT,
            sum(case when city='TN' and result='Ready' then 1 else 0 end) as No_Ready,
            sum(case when city='TN' and result='Sold' then 1 else 0 end) as No_sold,
            sum(case when city='TN' and result='Missing' then 1 else 0 end) as No_Missing
from source

但问题是,如果城市被添加,我必须再写一个UNION ALL。无论如何,我可以对 CITY 列中的所有可用城市执行此操作,而无需为每个城市添加 union all

一种快速的方法是尝试子查询:

select City,
count(*) as CNT,
(select count(*) from Sample where Sample.City = s.City and result = 'Ready') as No_Ready,
(select count(*) from Sample where Sample.City = s.City and result = 'Sold') as No_Sold,
(select count(*) from Sample where Sample.City = s.City and result = 'Missing') as No_Missing,
from Sample s
group by City

注意:holder 查询性能可能比这个更好

试试这个

select city,
COUNT(*) as CNT,
            sum(case when result='Ready' then 1 else 0 end) as No_Ready,
            sum(case when result='Sold' then 1 else 0 end) as No_sold,
            sum(case when  result='Missing' then 1 else 0 end) as No_Missing
FROM source
group by city