Найдите счетчики для всех городов - PullRequest
1 голос
/ 09 июля 2020

У меня есть таблица Fiddle здесь

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

Logi c просто подсчитывает каждый результат для каждого город. Теперь я получаю результат с запросом ниже

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, не добавляя объединение всех для каждого города

Ответы [ 2 ]

1 голос
/ 09 июля 2020

Попробуйте это

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
0 голосов
/ 09 июля 2020

Быстрый подход - попытка подзапросов:

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

Примечание: производительность запроса держателя может быть лучше, чем у этого

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...