select out.a,out.b from out
pivot (count([event]) for [date] in ([Mon],[Tues])) as event_count
group by out.a,out.b
在执行此查询时,我收到以下错误:
The multipart identifier out.a,out.b could not be bound
最佳答案
删除 GROUP BY
子句以及列 a
和 b
的别名 out
,如下所示:
select a, b, [Mon], [Tues]
from out
pivot
(
count([event])
for [date] in ([Mon],[Tues])
) as event_count;
SQL Fiddle Demo
请注意:使用PIVOT
表运算符时,您不需要显式指定分组元素,在您的情况下为a, b
或者在源表中,您需要将其从查询和源表中删除。 PIVOT
运算符会自动找出您想要GROUP BY
的列,这些列是在date
或date
中未指定的列。在您的情况下,聚合元素是事件
,其余的将是分组列。
这就是为什么您必须显式列出列名而不是 FROM out
,以防表 out
包含除 a、b、date、事件
。在这种情况下,您必须这样做:
select a, b, [Mon], [Tues]
from
(
SELECT a, b, "date", "event"
FROM out
) t
pivot
(
count([event])
for [date] in ([Mon],[Tues])
) as event_count;
关于sql - 带分组依据的数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13853880/