我有一个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
非常令人沮丧时所涉及的格式和猜测。
有人能建议一个更好的查询,以便以良好的格式返回数据吗?
答案 0 :(得分:4)
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(向下滚动以查看旋转结果)。
答案 1 :(得分:2)
怎么样......
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