在While循环中分组,SQL Server

时间:2016-09-28 14:10:08

标签: sql sql-server tsql while-loop grouping

我一直在构建一个while循环来填充大量数据,而且我在查询中遇到分组困难 - 我想在Membership_Level上添加一个组,但每次返回相同的值时(每个级别的总数)。

任何人都可以帮助我吗?

提前谢谢!!!

DECLARE @Counter int
DECLARE @NumPerson int

SET @Counter = 1

WHILE @Counter <= 12

BEGIN
    SET @NumPerson = (SELECT
    SUM(Amount)
    FROM [NewMember]
    WHERE LEFT([PERIOD], 4) = 2016
    AND GRADE_STATUS = 'N'
    AND RIGHT([Period], 2) = @Counter)

    SELECT
    *
    FROM (SELECT
    CAST(@NumPerson AS varchar(6)) AS 'Number',
    CASE
        WHEN LEN(CAST(@Counter AS varchar(2))) = 1 THEN '0' + CAST(@Counter AS varchar(2))
        ELSE CAST(@Counter AS varchar(2))
    END AS 'Month') s
    JOIN (SELECT
    MAX('1') AS NGroup,
    [PERIOD],
    RIGHT([Period], 2) AS 'Month',
    MEMBERSHIP_LEVEL
    FROM [NewMember]
    WHERE LEFT([PERIOD], 4) = 2016
    AND GRADE_STATUS = 'N'
    GROUP BY    [MEMBERSHIP_LEVEL],
                [PERIOD],
                RIGHT([Period], 2)) t
    ON s.[Month] = t.[Month]
    SET @Counter = @Counter + 1
END

0 个答案:

没有答案