2015-08-26 154 views
-1

我想在表的末尾添加總目標列,但無法通過CUBE設置它,因爲那麼它表示b.x無效。我該怎麼做?SQL GROUP BY WITH CUBE

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

你可以改變你的內部查詢財產以後這樣的: -

Select Home as Team, [Week] as Weeks, [Home Score] as Goals From Fixture 
group by Home,Week, [Home Score] 
UNION ALL 
Select Away as Team, [Week] as Weeks, [Away Score] as Goals From Fixture 
group by Away,Week, [Away Score] 
UNION ALL 
Select 'Total', NULL, SUM([Home Score]) + SUM ([Away Score]) as 'Total Goals' From Fixture 

這個邏輯可以幫助你。