我有一个 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
这是相当令人沮丧的。
谁能建议一个更好的查询,以良好的格式返回数据?
怎么样...
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。
- 根据表的索引方式,它可能需要大量的排序空间,如果没有足够的可用空间,则可能会失败。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)