我有一个包含大约 5 亿行数据的 SQL Server 2008 R2 数据库,它目前看起来像这样
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
所涉及的格式和猜测工作这是非常令人沮丧的。任何人都可以提出一个更好的查询来以良好的格式返回数据吗?
最佳答案
有pivot Sql Server 中的功能。例如,如果您有 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 (向下滚动以查看旋转结果)。
关于sql-server - SQL Server : splitting the results of GROUP BY into a separate columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11006449/