如何在PIVOT中使用多个功能或使用多个PIVOTS

时间:2018-02-01 16:04:31

标签: sql sql-server tsql

我有以下查询,在大多数部分工作正常,但我遇到了第二个PIVOT的问题。

理想情况下,它应该返回将questionId 12的列设置为1的所有实例的计数。这是一个位字段。

但在所有情况下,它都会返回1作为结果。

SELECT 
            [1] as GeneralFeedback,
            [3] as FoodRating,
            [4] as DrinksRating,
            [5] as RestaurantAmbience,
            [6] as ServiceRating,
            [7] as BookingService,
            [12] as RecommendationsCount,
            [13] as Rating,
            [525] as ValueForMoney, 
            [526] as LocationRating,
            ReviewCount
            FROM
            (   SELECT QR.QuestionId,
                       CONVERT(DECIMAL, QR.RatingScaleOptionId) AS rating,
                       (COUNT(1) OVER ()) / 10 ReviewCount,
                       CASE WHEN QR.YesOrNoOptionAnswer = 1 THEN 1 ELSE 0 END as RecommendationsCount
                FROM QuestionResponse QR
                     INNER JOIN SurveyResponse sr ON QR.SurveyResponseId = SR.SurveyResponseId
                WHERE SR.StatusId IN(5, 7)
                     AND QR.QuestionId IN(1, 3, 4, 5, 6, 7, 12, 13, 525, 526)
                AND SR.RestaurantNetworkId = 101368
            ) AS SourceTable 
            PIVOT(AVG(rating) FOR QuestionId IN([1],[3],[4],[5],[6],[7],[13],[525],[526])) AS PivotTable1
            PIVOT(COUNT(RecommendationsCount) FOR RecommendationsCount IN([12])) AS PivotTable2

内部查询结果如下图所示,请记住,共有15个实例,其中RecommendationsCount为1,1个实例为0,所有其他实例为NULL。

enter image description here

以下是整个查询的结果: enter image description here

1 个答案:

答案 0 :(得分:1)

使用条件聚合对自己进行旋转编码。

SELECT
  SurveyID_Or_RestaurantID_Or_Something,
  AVG(CASE WHEN QuesitonID = 1  THEN Rating               END)   AS GeneralFeedback,
  AVG(CASE WHEN QuesitonID = 3  THEN Rating               END)   AS FoodRating,
  ...
  SUM(CASE WHEN QuestionID = 12 THEN RecommendationsCount END)   AS RecommendationsCount
FROM
  YourTablesAndJoins
GROUP BY
  SurveyID_Or_RestaurantID_Or_Something

这是有效的,因为所有ELSE NULL语句中都有 隐式 CASE < / strong>聚合函数忽略那些NULL值。