我有以下示例表
User | Event
=============
Bob EventX
Steve EventA
Bob EventC
Jane EventB
Jane EventA
Bob EventC
我想构建一个真值表,告诉我特定用户是否触发了特定事件
User | EventA | EventB | Event C | Event X
===============================================
Bob False False True True
Steve True False False False
Jane True True False False
在SQL中有没有办法解决这个问题,而不必编写代码来构建这个表?
谢谢
答案 0 :(得分:1)
尝试类似:
SELECT user, max(iif(event='EventA','True','False')) as 'EventA', ..
FROM events
GROUP BY user;
答案 1 :(得分:1)
您可以使用Pivot(下面的MSSQL示例)执行此操作。您必须在Pivot FOR(..)列表中指定每列
DECLARE @Events AS TABLE
(
EventId VARCHAR(20)
,UserName VARCHAR(100)
)
INSERT INTO @Events (EventId, UserName) VALUES('EventA','BOB')
INSERT INTO @Events (EventId, UserName) VALUES('EventA','STEVE')
INSERT INTO @Events (EventId, UserName) VALUES('EventB','STEVE')
INSERT INTO @Events (EventId, UserName) VALUES('EventB','STEVE')
INSERT INTO @Events (EventId, UserName) VALUES('EventB','STEVE')
SELECT
PivotedList.UserName
,CASE WHEN PivotedList.EventA IS NULL THEN 'FALSE' ELSE 'TRUE' END AS EventA
,CASE WHEN PivotedList.EventB IS NULL THEN 'FALSE' ELSE 'TRUE' END AS EventB
FROM
@Events AS Events
PIVOT
(
MAX(EventId)
FOR EventId IN ([EventA],[EventB])
) AS PivotedList
结果:
UserName EventA EventB
=================================
BOB TRUE FALSE
STEVE TRUE TRUE