答案 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