【问题标题】:SQL Server : splitting the results of GROUP BY into a separate columnsSQL Server:将 GROUP BY 的结果拆分为单独的列
【发布时间】:2012-06-13 13:09:01
【问题描述】:

我有一个 SQL Server 2008 R2 数据库,其中包含大约 5 亿行数据,目前看起来像这样

ID          Eventtype
201         1
201         3
201         4
201         1
201         1
664         1
664         0
664         1
664         3

我似乎找不到可以以这种格式返回数据的查询:

ID         Event0   Event1  Event2  Event3  Event4
201        0        3       0       1       1
664        1        2       0       1       0

这是我目前所得到的:

select distinct ID as ID, count(EventType)
from database.dbo.events 
group by questID, EventType

像这样向我吐出数据:

ID       EventType
201      0
201      3
201      0
201      1
201      1
664      1
664      2
664      0
etc.

这确实显示了我需要的所有数据,但是在试图找出 EventType 是哪个时所涉及的格式和猜测非常令人沮丧。

谁能推荐一个更好的查询,以良好的格式返回数据?

【问题讨论】:

  • 这是哪个版本的Sql Server?

标签: sql-server sql-server-2008-r2


【解决方案1】:

诸如...之类的东西怎么样?

select ID, sum(Event0), sum(Event1), sum(Event2), sum(Event3), sum(Event4)
from (
    select ID, 
        case EventType when 0 then 1 else 0 end as Event0,
        case EventType when 1 then 1 else 0 end as Event1,
        case EventType when 2 then 1 else 0 end as Event2,
        case EventType when 3 then 1 else 0 end as Event3,
        case EventType when 4 then 1 else 0 end as Event4
    from dbo.events
) E
group by ID
  • 假设恰好有 5 种事件类型,编号从 0 到 4。
  • 根据表的索引方式,它可能会占用大量的排序空间,并且如果没有足够的空间可用,可能会失败。

【讨论】:

  • 太棒了,谢谢!这非常有效。 Nikola 的回复也是正确的,但是数据透视表需要 14 分钟才能运行,而 joshp 的案例版本需要 6 分钟。
【解决方案2】:

Sql Server 中有pivot 功能。例如,如果您有 6 个不同的事件,则可以使用:

select ID, [0], [1], [2], [3], [4], [5]
from events
pivot 
(
  -- aggregate function to apply on values
  count(EventType) 
  -- list of keys. If values of keys are not fixed,
  -- you will have to use dynamic sql generation 
  for EventType in ([0], [1], [2], [3], [4], [5])
) pvt

有关动态枢轴生成,请参阅this SO post

顺便说一句,我相信您的原始查询应该是:

select ID, EventType, count(EventType)
from events 
group by ID, EventType
order by ID, EventType

您可以在@Sql Fiddle 看到它的实际效果(向下滚动查看旋转结果)。

【讨论】:

  • 谢谢!这确实工作得很好,运行时间比 joshp 的案例版本要长一些。
猜你喜欢
  • 2019-07-27
  • 1970-01-01
  • 2013-08-02
  • 1970-01-01
  • 1970-01-01
  • 2015-05-11
  • 2022-06-15
  • 2021-04-27
  • 2016-01-11
相关资源
最近更新 更多