4

在我的 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?我还没有找到任何有用的东西...

谢谢你的帮助...

4

2 回答 2

8
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

于 2013-09-24T13:02:15.300 回答
6

我发现这更容易自己理解,也可以在 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)
于 2014-06-08T20:28:25.003 回答