数据透视表与分组

时间:2012-12-13 06:00:45

标签: sql sql-server sql-server-2008 pivot

select out.a,out.b from out
pivot (count([event]) for [date] in ([Mon],[Tues])) as event_count
group by out.a,out.b

执行此查询时出现以下错误:

  

多部分标识符out.a,out.b无法绑定

3 个答案:

答案 0 :(得分:7)

删除GROUP BY子句以及列outa的别名b,如下所示:

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或汇总元素event中未指定的列。在你的情况下,其余的将是分组列。

这就是为什么你必须明确列出列的名称而不是FROM out,因为表out包含a, b, date, event以外的列。在这种情况下,您必须这样做:

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;

答案 1 :(得分:2)

听起来你需要在[星期一]和[星期二]

上替换out.a
SELECT [Mon], [Tues]
FROM out
PIVOT (
       COUNT([event]) FOR [date] in ([Mon],[Tues])
       ) AS event_count

SQLFiddle上的演示

答案 2 :(得分:1)

我不确定您的查询,但可能是您正在寻找的

Select a,b, [Mon],[Tues] from 
(
  Select a,b,date,event from out 
  group by a,b,date,event
)L
PIVOT
(
  count(event) for [date] in ([Mon],[Tues]) 
)  event_count