Mysql:在group by中添加条件

时间:2014-03-03 11:25:54

标签: mysql

通过在查询中使用 group by source子句,我得到以下结果。

Source  No_of_users
  1         2
  2         7
  3         3
  4         34
  5         21

如何对源的某些值进行分组,即输出如下:

Source   No_of_users
  1+2         9
  3+5         24
  4           34

需要建议。

4 个答案:

答案 0 :(得分:0)

是的,像工会一样:

SELECT SUM(no_of_users) AS some_sum from some_table where source in (1,2,3)
UNION
SELECT SUM(no_of_users) AS some_sum from some_table where source in (4,5,6)
UNION
SELECT SUM(no_of_users) AS some_sum from some_table where source in (6,7,8)

答案 1 :(得分:0)

Try This......

with cte as (
    select
        case Name
            when '2' then '1'
            when '5' then '3'
              //add more combinations ....
            else Name
        end as Name
    from table
)
select Name, count(*)
from cte
group by Name

答案 2 :(得分:0)

这可以通过使用嵌套SELECT强制Source列到适当的值,然后对结果行进行分组来实现:

SELECT  Source,
        SUM(No_of_users)
  FROM  (SELECT  CASE
                   WHEN Source = 1 THEN '1+2'
                   WHEN Source = 2 THEN '1+2'
                   WHEN Source = 3 THEN '3+5'
                   WHEN Source = 5 THEN '3+5'
                   ELSE Source
                 END AS Source,
                 No_of_users
         FROM  `Table`) AS A
  GROUP BY Source

SQL Fiddle可用here来演示。

答案 3 :(得分:0)

在MySQL中,你可以这样做:

SELECT (CASE WHEN Source in (1, 2) THEN '1+2'
             WHEN Source in (3, 5) THEN '3+5'
             ELSE Source
        END) as Source,
       SUM(No_of_users) as No_of_users
FROM  `Table` t
GROUP BY Source
ORDER BY Source;