将枢轴上的计数转换为位/标志?
Convert count on a pivot to a bit / flag?
我有一个有效的数据透视表查询:
SELECT * FROM
(
select [cid], [cid] as c, [Category] from [MyTbl] where [Conditional] = 0
)
as src PIVOT(COUNT(c) FOR [Category] in ([SciFi],[Horror],[Comedy])) AS piv
太棒了,它会产生这样的东西:
cid | SciFi | Horror | Comedy
-----------------------------
1 0 3 0
2 1 2 1
3 6 2 4
但实际上我不想要计数,我只想要一个 true 或 false 标志(最好是 0 或 1)
cid | SciFi | Horror | Comedy
-----------------------------
1 0 1 0
2 1 1 1
3 0 1 1
我尝试在 case 语句中包装 count(c)
位,但我只是遇到语法错误 - 假设枢轴不是这样工作的。
我会推荐条件聚合。它比 vendor-specific pivot
语法灵活得多,可以让你轻松地做你想做的事:
select cid,
max(case when category = 'SciFi' then 1 else 0 end) SciFi,
max(case when category = 'Horror' then 1 else 0 end) Horror,
max(case when category = 'Comedy' then 1 else 0 end) Comedy
from mytbl
where conditional = 0
group by cid
我有一个有效的数据透视表查询:
SELECT * FROM
(
select [cid], [cid] as c, [Category] from [MyTbl] where [Conditional] = 0
)
as src PIVOT(COUNT(c) FOR [Category] in ([SciFi],[Horror],[Comedy])) AS piv
太棒了,它会产生这样的东西:
cid | SciFi | Horror | Comedy
-----------------------------
1 0 3 0
2 1 2 1
3 6 2 4
但实际上我不想要计数,我只想要一个 true 或 false 标志(最好是 0 或 1)
cid | SciFi | Horror | Comedy
-----------------------------
1 0 1 0
2 1 1 1
3 0 1 1
我尝试在 case 语句中包装 count(c)
位,但我只是遇到语法错误 - 假设枢轴不是这样工作的。
我会推荐条件聚合。它比 vendor-specific pivot
语法灵活得多,可以让你轻松地做你想做的事:
select cid,
max(case when category = 'SciFi' then 1 else 0 end) SciFi,
max(case when category = 'Horror' then 1 else 0 end) Horror,
max(case when category = 'Comedy' then 1 else 0 end) Comedy
from mytbl
where conditional = 0
group by cid