I need to query the Student (STU) & Programs (PGM) tables and return one combined record per ID, even if there are multiple PGM records per ID. I thought about using GROUP BY STU.ID, STU.FN, STU.LN, but then I’m not sure how to use PGM.CD in the SELECT, since it’s not an aggregate function or in the GROUP BY clause.`
The PGM table may or may not have records. My query below returns these possible results:
- If there are no
PGMrecords, only one result perIDis returned and
thePGM.CDcolumn returnsNULL(or''per theCASE). - If there’s only one record in the
PGMtable, andPGM.CD = 200
('DLA'per theCASE), then only one result perIDis returned. - If there’s only one record in the
PGMtable, andPGM.CD <> 200
(''per theCASE), then only one result perIDis returned. - If there is more than one record in the
PGMtable (perID), i.e.
121, 200, 156, this produces multiple rows perID.
I need a query to return only one row per ID, combining the results of the PGM.CD column. The PGM.CD column should only return '' or 200 ('DLA' per the CASE)
SELECT STU.ID, STU.FN, STU.LN,
CASE PGM.CD
WHEN '200' THEN 'DLA'
ELSE ''
END
FROM STU
LEFT JOIN PGM
ON STU.ID = PGM.PID
This is what my query returns (Without the CASE modifying PGM.CD):
STU.ID STU.FN STU.LN PGM.CD
1000 Bruce Wayne NULL
1001 Clark Kent 200
1002 Barry Allen 151
1002 Barry Allen 101
1003 Hal Jordan 126
1003 Hal Jordan 200
1003 Hal Jordan 101
This is what my query returns (With the CASE modifying PGM.CD):
STU.ID STU.FN STU.LN PGM.CD
1000 Bruce Wayne
1001 Clark Kent DLA
1002 Barry Allen
1002 Barry Allen
1003 Hal Jordan
1003 Hal Jordan DLA
1003 Hal Jordan
I need it to return this:
STU.ID STU.FN STU.LN PGM.CD
1000 Bruce Wayne
1001 Clark Kent DLA
1002 Barry Allen
1003 Hal Jordan DLA
I hope all of this makes sense. Thanks for the help.
Anthony
You should use a simple query like this:
Try to use the SQL Fiddle(!) it is a big help in a quick answer.
I made an Example for you how is it working. Pls check it.