开发者

Selecting values from one column based on a different columns value

开发者 https://www.devze.com 2023-04-08 15:16 出处:网络
Having trouble stating my problem succinct开发者_高级运维ly here, so I\'ll just give an example.

Having trouble stating my problem succinct开发者_高级运维ly here, so I'll just give an example.

Let's say I have a DB2 table about Students:

Name           Class          Grade
Billy J        Econ           A
Sarah S        Maths          B
Greg X         Computes       A-
Billy J        Maths          D
Greg X         Maths          C+

And I want to retrieve those students that are in both Econ and Maths, and display the information thusly:

Name       Maths Grade       Econ Grade
Billy J    D                 A

How in the world can I accomplish this?


This solution will solve the problem for the two classes you named:

SELECT Name, Math.Grade AS MathsGrade, Econ.Grade AS EconGrade
  FROM Students Math INNER JOIN Students Econ ON Math.Name = Econ.Name
  WHERE Math.Class = 'Maths' AND Econ.Class = 'Econ'

The only thing that this solution doesn't do is include the spaces in your derived column names. You can do that by writing Maths Grade and Econ Grade in whatever characters DB2 uses for identifier quotes.

To be included students must have both a Maths and an Econ grade.


SELECT * from Students
where id in 
(SELECT id from Students where Class = 'Econ')
AND id in
(SELECT id from Students where Class = 'Math');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号