Группирование определенных строк в одну строку в sqlite - PullRequest
0 голосов
/ 24 августа 2018

Это запрос, который получил мне этот результат.

 SELECT
    country,
    COUNT(DISTINCT(customer_id)) total_customers
FROM customer c
GROUP BY 1
ORDER BY 2 DESC

    country   total_customers

1   India       2
2   Portugal    2
3   Argentina   1
4   Australia   1
5   Austria     1
6   Belgium     1
7   Chile       1

Как я могу сгруппировать все 1 в категорию Другие?

Желаемый выход: страна клиентов

1   India       2
2   Portugal    2
3   Others      5

Ответы [ 4 ]

0 голосов
/ 24 августа 2018

Вы должны поместить свой запрос в другой запрос для повторного агрегирования. GROUP BY a CASE, который возвращает страну, или 'Other' на основе количества. ORDER BY становится немного сложнее, так как вам придется использовать вышеупомянутый случай в нем, чтобы отсортировать Others после всех других стран. Сначала проверьте, возвращает ли CASE 'Others', затем возвращает более высокое значение, иначе более низкое. Затем сортируйте по CASE.

Это должно выглядеть примерно так:

SELECT CASE x.total_customers
         WHEN 1 THEN
           'Others'
         ELSE
           x.country
       END country,
       sum(total_customers) total_customers
       FROM (SELECT c.country,
                    count(DISTINCT c.customer_id) total_customers
                    FROM customer c
                    GROUP BY c.country) x
       GROUP BY CASE x.total_customers
                  WHEN 1 THEN
                    'Others'
                  ELSE
                    x.country
                END
       ORDER BY CASE
                  WHEN CASE x.total_customers
                         WHEN 1 THEN
                           'Others'
                         ELSE
                           x.country
                        END = 'Others' THEN
                    1
                  ELSE
                    -1
                END,
                CASE x.total_customers
                  WHEN 1 THEN
                    'Others'
                  ELSE
                    x.country
                END;

(Не проверено, поскольку не были предоставлены DDL или данные образца.)

0 голосов
/ 24 августа 2018

Вам нужно case с group by предложением:

select (case when customers = 1 then 'Others' else country end) country,
       sum(customers) customers
from table t
group by (case when customers = 1 then 'Others' else country end);

РЕДАКТИРОВАТЬ: Например, предыдущий запрос будет реализован с подзапросом.

Но для этого вы можете сделать:

select (case when country in ('India','Portugal') then country else 'others' end) as country,
       count(distinct customer_id) as customers
from table t
group by (case when country in ('India','Portugal') then country else 'others' end)
0 голосов
/ 24 августа 2018

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

select case when customers not in ('India',
'Portugal') then 'Others' else country end as country,
       sum(customers) as customers
from t
group by case when customers not in ('India',
'Portugal') then 'Others' else country end
0 голосов
/ 24 августа 2018

Используйте case и group by, дважды:

select (case when total_customers = 1 then 'Others' else country end) as country,
       sum(total_customers) as customers
from (select country,
             count(distinct customer_id) as total_customers
      from customer c
      group by country
     ) c
group by (case when total_customers = 1 then 'Others' else country end);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...