如何替换第一行以外的分组列中的所有值

时间:2016-05-13 04:11:31

标签: sql sql-server tsql

我有这样的表:

ID   Region  CreatedDate   Value
--------------------------------
1    USA     2016-01-01    5
2    USA     2016-02-02    10
3    Canada  2016-02-02    2
4    USA     2016-02-03    7
5    Canada  2016-03-03    3
6    Canada  2016-03-04    10
7    USA     2016-03-04    1
8    Cuba    2016-01-01    4

我需要按年份和月份对按ValueRegion分组的列CreatedDate求和。结果将是

Region  Year   Month  SumOfValue
--------------------------------
USA     2016   1       5
USA     2016   2      17
USA     2016   3       1
Canada  2016   2       2
Canada  2016   3      13
Cuba    2016   1       4

但我想用第一个符合行的空字符串替换列Region中的所有重复值。完成结果必须是:

Region  Year   Month  SumOfValue
--------------------------------
USA     2016   1          5
        2016   2         17
        2016   3          1
Canada  2016   2          2
        2016   3         13
Cuba    2016   1          4

感谢您提供解决方案。如果解决方案也将替换为Year

,那将是有利的

1 个答案:

答案 0 :(得分:2)

您需要使用SUMGROUP BY来获取SumOfValue。对于格式设置,您可以使用ROW_NUMBER

WITH Cte AS(
    SELECT
        Region,
        [Year]  = YEAR(CreatedDate),
        [Month] = MONTH(CreatedDate),
        SumOfValue = SUM(Value),
        Rn = ROW_NUMBER() OVER(PARTITION BY Region ORDER BY YEAR(CreatedDate), MONTH(CreatedDate))
    FROM #tbl
    GROUP BY
        Region, YEAR(CreatedDate), MONTH(CreatedDate)
)
SELECT
    Region = CASE WHEN Rn = 1 THEN c.Region ELSE '' END,
    [Year],
    [Month],
    SumOfValue
FROM Cte c
ORDER BY
    c.Region, Rn

ONLINE DEMO

虽然这可以在TSQL中完成,但我建议你在应用程序端进行格式化。

Query遵循与OP相同的顺序。