SQL GROUP BY WITH CUBE

时间:2015-08-26 14:26:48

标签: sql-server tsql group-by pivot-table dynamic-pivot

我想在表的末尾添加一个总目标列,但无法通过CUBE设置它,因为它表示b.x无效。我该怎么办?

 DECLARE @Weeks VARCHAR(MAX) = ''
    SELECT @Weeks += (QUOTENAME([Week]) + ',') 
FROM
(Select Distinct [Week] from Fixture
) as z
SET @Weeks = LEFT(@Weeks, LEN(@Weeks) - 1)
print @Weeks

DECLARE @SQL NVARCHAR(MAX) = ''
SET @SQL = '

    select *
    from
    (
    Select Home as Team, [Week] as Weeks, [Home Score] as Goals From Fixture
    group by Home,Week, [Home Score]
    UNION
    Select Away as Team, [Week] as Weeks, [Away Score] as Goals From Fixture
    group by Away,Week, [Away Score]
    ) as A
PIVOT
(
    MAX(Goals)
For Weeks
    IN(' + @Weeks + ')
    )b


'
exec (@SQL)

0 个答案:

没有答案