查找不同城市的调查总和

时间:2018-07-20 22:05:28

标签: sql sql-server group-by sum

CityMastr
    Serno  City
    1      Mumbai
    2      New York
    3      Madrid

UserMstr
    UserId  City
    1        1 
    2        2

SurveyMastr
UserId   score  Question
1          10       1   
1          5        2
1          0        3
1          10       4
2          5        1
2          5        2
2          5        3
2          0        4

我想要类似

Questionid Mumbai  New York  Madrid
1          10        5        0
2          5         5        0
3          0         5        0
4         10         0        0

问题是我将case与sum一起使用,但是我不得不将其分组,并且一直给我8行。另外,我必须使用静态的Case。每次添加新城市时,我都必须添加新案例。有没有办法动态地做到这一点?

1 个答案:

答案 0 :(得分:4)

您将需要为此使用动态SQL。像......

Declare   @Cols         NVARCHAR(MAX)
        , @IsNullCols   NVARCHAR(MAX)
        , @Sql          NVARCHAR(MAX);

-- For PIVOT IN Clause
 SELECT @Cols =  STUFF( (SELECT DISTINCT ',' + QUOTENAME(City)
                        FROM CityMastr
                        FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,1,'');

 -- For the SELECT Clause
 SELECT @IsNullCols =  STUFF( (SELECT DISTINCT ', ISNULL( ' + QUOTENAME(City) + ' , 0) AS ' + QUOTENAME(City)
                        FROM CityMastr
                        FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,1,'');


SET @Sql = N' WITH X AS (
        SELECT    sm.Question
                , ISNULL(sm.Score , 0)  AS Score
                , cm.City
        FROM SurveyMastr sm
        INNER JOIN UserMstr um ON sm.UserId = um.UserId
        INNER JOIN CityMastr cm ON um.City = cm.Serno
)
SELECT Question , ' + @IsNullCols + N'
FROM X
  PIVOT ( SUM(Score)
          FOR City
          IN (' + @Cols + N')
          )p
ORDER BY Question'

        Exec sp_executesql @sql 

结果集

╔══════════╦════════╦════════╦══════════╗
║ Question ║ Madrid ║ Mumbai ║ New York ║
╠══════════╬════════╬════════╬══════════╣
║        1 ║      0 ║     10 ║        5 ║
║        2 ║      0 ║      5 ║        5 ║
║        3 ║      0 ║      0 ║        5 ║
║        4 ║      0 ║     10 ║        0 ║
╚══════════╩════════╩════════╩══════════╝