SQL GROUP BY一列的不同值

时间:2013-09-24 12:59:41

标签: sql sql-server group-by

在我的SQL Server上我得到了下表 - 简化:

year    month    category    value
2009    9        1           10
2009    9        2           20
2009    9        3           40
...     ...      ...         ...

现在我想按年,月和类别(1 + 2,3,...)进行分组,以便我的结果如下所示:

year    month    category    value
2009    9        1+2         30
2009    9        3           40
...     ...      ...         ...

无法对表格进行任何更改。此外,SQL运行得很快很重要......

如何制作此GROUP BY?我找不到任何有用的东西......

感谢您的帮助......

2 个答案:

答案 0 :(得分:6)

with cte as (
   select
       year, month, value,
       case
           when category in (1, 2) then '1+2'
           else cast(category as varchar(max))
       end as category
   from Table1
)
select
    year, month, category, sum(value)
from cte
group by year, month, category

select
    t.year, t.month, isnull(c.category, t.category), sum(value)
from Table1 as t
    left outer join (values
        (1, '1+2'),
        (2, '1+2')
    ) as c(id, category) on c.id = t.category
group by t.year, t.month, isnull(c.category, t.category)

<强> sql fiddle demo

答案 1 :(得分:2)

我发现自己更容易理解这一点,也可以在sqlite中轻松实现

SELECT
    t.year,
    t.month,
    (CASE WHEN t.category = 1 OR t.category = 2 THEN '1+2' ELSE t.category END) as category,
    sum(value) AS value
FROM table_name AS t 
GROUP BY (CASE WHEN t.category = 1 OR t.t.category = 2 THEN '1+2' ELSE t.category END)