【问题标题】:SQL GROUP BY different values of one coloumnSQL GROUP BY 一列的不同值
【发布时间】:2013-09-24 12:59:40
【问题描述】:

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

感谢您的帮助...

【问题讨论】:

  • 您如何决定应该聚合哪些类别?还是总是 1 和 2?
  • 总是1+2等等...

标签: sql sql-server group-by


【解决方案1】:
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、3+4、5+6、7+8+9 是不是没有机会在没有辅助表的情况下执行此操作?!
【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2012-02-29
    • 1970-01-01
    相关资源
    最近更新 更多