Share via

Query help!

Harry 20 Reputation points
2023-09-27T06:17:34.14+00:00
CREATE TABLE StuScore 
(   
    ID int IDENTITY(1,1),
    studentId int,
    course varchar(10),
    Score int
);
INSERT INTO StuScore 
Values
(1,'History',80),
(1,'Philosophy',76),
(1,'Math',84),
(2,'History',70),
(2,'Philosophy',66),
(2,'Math',92),
(3,'History',75),
(3,'Philosophy',78),
(3,'Math',80)

Without the ID column, I can easily get the result I want.

select * from StuScore as s
pivot (max(Score) for course in ([History],[Philosophy],[Math])) as t
studentId History Philosophy Math
1 80 76 84
2 70 66 92
3 75 78 80

However, after adding the ID column, the result of the query appears with more rows and a lot of Nulls. Why?

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

Anonymous
2023-09-27T06:24:59.8733333+00:00

Hi @Harry

A new column changes the query result. This is a normal thing.

Depending on your question, you need to include a 'Group By' in the original query.

How about this query:

select min(id) as id,studentId,max(History) as History,
       max(Philosophy) as Philosophy,max(Math) as Math
from StuScore as s
pivot (max(Score) for course in ([History],[Philosophy],[Math])) as t
group by studentId;

Best regards,

Percy Tang

Was this answer helpful?

1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 47,621 Reputation points
    2023-09-27T06:22:00.64+00:00

    after adding the ID column, the result of the query appears with more rows

    Then I guess you don't "GROUP BY" on the ID column, do you? Please post your complete SQL statement.

    Was this answer helpful?

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.