在sqlite中将某些行分组为一行

时间:2018-08-24 11:16:05

标签: sql sqlite

这是让我得到此结果的查询。

 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 :(得分:2)

两次使用casegroup 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);

答案 1 :(得分:1)

您需要let result = names.filter(o1 => !master.every(o2 => o1.name.split('|').includes(o2.value))); 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);

答案 2 :(得分:1)

您必须将查询放入另一个查询中才能再次聚合。 GROUP BYCASE,根据计数返回国家或地区'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或示例数据。)

答案 3 :(得分:0)

尝试一下:

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