应用STUFF函数后如何拆分列值的收入?

时间:2017-08-27 21:11:31

标签: sql sql-server

我有这个grid1 我使用STUFF函数来创建grid2 当我在2个填充列中的任何一个上应用过滤器时,我需要grid3结果。

enter image description here

1 个答案:

答案 0 :(得分:2)

以下能够生成Grid_2和Grid_3的结果,具体取决于过滤器选择。

IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL 
DROP TABLE #TestData;

CREATE TABLE #TestData (
    [UID] INT NOT NULL,
    [Year] INT NOT NULL,
    Geo CHAR(2) NOT NULL,
    Revenue MONEY NOT NULL 
    );

INSERT #TestData (UID, Year, Geo, Revenue) VALUES 
    (1234556, 2015, 'US', 1500),
    (1234556, 2016, 'IN', 1800),
    (1234556, 2017, 'FR', 1900);

-- SELECT * FROM #TestData td;

--=======================================================

DECLARE 
    @Year INT = NULL,
    @Geo CHAR(2) = NULL;

SELECT 
    td1.[UID],
    [Year] = MAX(STUFF(cy.ConcatYear, 1, 1, '')),
    Geo = MAX(STUFF(cg.ConcatGeo, 1, 1, '')),
    Revenue = SUM(td1.Revenue)
FROM
    #TestData td1
    CROSS APPLY (
            SELECT 
                CONCAT(',', td2.[Year])
            FROM
                #TestData td2
            WHERE 
                td1.[UID] = td2.[UID]
                AND (td2.[Year] = @Year OR @Year IS NULL)
                AND (td2.Geo = @Geo OR @Geo IS NULL)
            FOR XML PATH('')
            ) cy (ConcatYear)
    CROSS APPLY (
            SELECT 
                CONCAT(',', td3.Geo)
            FROM
                #TestData td3
            WHERE 
                td1.[UID] = td3.[UID]
                AND (td3.[Year] = @Year OR @Year IS NULL)
                AND (td3.Geo = @Geo OR @Geo IS NULL)
            FOR XML PATH('')
            ) cg (ConcatGeo)
WHERE 
    (td1.[Year] = @Year OR @Year IS NULL)
    AND (td1.Geo = @Geo OR @Geo IS NULL)
GROUP BY
    td1.[UID]
OPTION(RECOMPILE); 
  

@Year INT = NULL,@ Geo CHAR(2)= NULL; - 结果......

UID         Year            Geo        Revenue
----------- --------------- ---------- ---------------------
1234556     2015,2016,2017  US,IN,FR   5200.00
  

@Year INT = 2015,@ Geo CHAR(2)= NULL; - 结果......

UID         Year            Geo        Revenue
----------- --------------- ---------- ---------------------
1234556     2015            US         1500.00