将平均列添加到数据透视表SQL

时间:2017-03-27 06:58:32

标签: sql sql-server

以下是我的表t_Vote:

| CandidateID | AmbassadorID  | Rate |
|      A      |       P1      |  6   |
|      A      |       P2      |  3   |
|      B      |       P1      |  5   |
|      B      |       P2      |  8   |

做完Pivot后,这是我的输出:

|CandidateID | P1 | P2 |
------------------------
|     A      | 6  | 3  |
|     B      | 5  | 8  |

我想要实现的是下表:

|CandidateID | P1 | P2 | Average |
----------------------------------
|     A      | 6  | 3  |   4.5   |
|     B      | 5  | 8  |   6.5   |

以下是我在进行支点时的查询:

SELECT CandidateID, Name, [P1],[P2]
FROM
(
    SELECT Name, AmbassadorID, CandidateID, Rate
    FROM t_Vote INNER JOIN t_Candidate
    ON t_Vote.CandidateID = t_Candidate.ID
) SRC
PIVOT
(
    AVG(Rate)
    FOR AmbassadorID IN ([P1],[P2])
) AS nT

P.S。 为了避免混淆,我删除了问题中的一些列。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

 ;With cte as
  (
    SELECT CandidateID, Name, [P1],[P2]
    FROM
    (
      SELECT Name, AmbassadorID, CandidateID, Rate
      FROM t_Vote INNER JOIN t_Candidate
      ON t_Vote.CandidateID = t_Candidate.ID
    ) SRC
   PIVOT
    (
      AVG(Rate)
      FOR AmbassadorID IN ([P1],[P2])
    ) AS nT
  )

 Select CandidateID, Name, [P1],[P2],(([P1]+[P2])/2) as [Avg] from cte

您可以使用临时表执行相同操作。您可以在https://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx

上找到有关cte的更多信息