动态数据透视表在T-SQL中使用多维数据集添加总计

时间:2015-08-27 08:01:57

标签: sql-server tsql group-by pivot cube

我正在做关于T-SQL的家庭作业。作业是关于显示每周为球队得分的所有目标。我设法做到了,但问题是,最后,他们想要一个名为total的行,显示每个团队在整个赛季中得分的所有目标。我尝试使用CUBE,但它没有成功。我的代码是:

 DECLARE @Weeks VARCHAR(MAX) = ' '
SELECT @Weeks += (QUOTENAME([Week]) + ',')
FROM(
SELECT DISTINCT [WEEK] from Fixture
) as a
SET @Weeks = LEFT(@Weeks, LEN(@Weeks) - 1)

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)

我有一个名为fixture的数据表,列是这样的: 周,主页,离开,主场比分,客场得分。

这个表适用于每周的目标但是当涉及行总数时,我无法弄清楚如何去做。我的老师说你可以使用GROUP BY ....和CUBE,但我无法弄清楚如何做到这一点。顺便说一下@Weeks打印如下:  [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13 ],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25], [26],[27],[28],[29],[30],[31],[32],[33],[34]

0 个答案:

没有答案