使用数据透视表获取无效的列名称

时间:2013-11-22 21:15:08

标签: sql-server

我有这个SQL:

Select FirstName, LastName, Hours, Case When DatePart(Weekday, Date) = 1 
             Then Date - 6 
             Else Date - DatePart(Weekday, Date) + 2 
             End [WeekOf], IsNull([Week44], 0) as [Week44], IsNull([Week45], 0) as [Week45], IsNull([Week46], 0) as [Week46], IsNull([Week47], 0) as [Week47], IsNull([Week48], 0) as [Week48]
             from (
             Select FirstName, LastName, Hours, Date, 'Week' + 
             Case When DatePart(Weekday, Date) = 1 
             Then Cast(DatePart(ww, Date - 6) as nvarchar(max))
             Else Cast(DatePart(ww, Date - DatePart(Weekday, Date) + 2) as nvarchar(max))
             End WeekNo
             From Entry
             Where Date between '11/1/2013' and '11/30/2013'
             ) alpha
 pivot (
sum(Hours)
for WeekNo in ([week44], [week45], [week46], [week47], [week48])
) p

据我所见,一切都很好,但我一直收到这个错误:

Msg 207, Level 16, State 1, Line 1
Invalid column name 'Hours'.

3 个答案:

答案 0 :(得分:4)

您不能将聚合列用作非旋转列。您不能在结果集中将小时数作为列。我认为逻辑上有问题。

答案 1 :(得分:0)

试试这个:

Select FirstName
    , LastName
    , [week44], [week45], [week46], [week47], [week48]
from 
(
    Select FirstName
        , LastName
        , Hours
        , Date
        , 'Week' + 
            Case 
                When DatePart(Weekday, Date) = 1 Then Cast(DatePart(ww, Date - 6) as nvarchar(max))
                Else Cast(DatePart(ww, Date - DatePart(Weekday, Date) + 2) as nvarchar(max))
            End WeekNo
    From Entry
    Where Date between '11/1/2013' and '11/30/2013'
) alpha
pivot 
(
sum(Hours)
for WeekNo in ([week44], [week45], [week46], [week47], [week48])
) p

这笔交易是[Hours]数据现在位于[weekXX]列中,不再是可供检索的数据元素。

答案 2 :(得分:-1)

我相信你只需要包含关键字[小时],[日期],[工作日]。