1

The following is my table t_Vote:

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

After doing a Pivot this is my output:

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

What I want to achieve is the following table:

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

Here is my query in doing the pivot:

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. I removed some of the columns in the question just to avoid confusion.

3
  • Why dont you try putting this in cte or temptable and add extra column for what you need! Commented Mar 27, 2017 at 7:00
  • what do you mean cte? Commented Mar 27, 2017 at 7:01
  • SELECT CandidateID, Name, [P1],[P2] ,([P1]+[P2])/2 as Average Commented Mar 27, 2017 at 7:06

1 Answer 1

1

You can go for this:

 ;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

You can do the same by using temp table. You can find more about cte on: https://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx

Sign up to request clarification or add additional context in comments.

3 Comments

So if i have more than 2 AmbassadorID i will also add it manually? in this query Select CandidateID, Name, [P1],[P2],(([P1]+[P2])/2) as [Avg] from cte
CAST((([P1] + [P2] + [P3])/3) AS FLOAT) AS AVG I added this, but still doesn't cast as float? why?
Convert P1, P2, P3 column itself in the cte to numeric or in float.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.