简体   繁体   中英

Writing an sql statement with a case

I am trying to write an sql statement to get the descriptions of two columns from a table. However, some of the rows in the a.code_2 column are null and don't need to get descriptions. My sql statement is shown below. It is only grabbing the columns that have a value in both code_1 and code_2 and not the rows in which a.code_2 is null.

 SELECT ID, CODE_1, B.CODE_DESC, CODE_2, C.CODE_DESC
     FROM TBLCODE A, TBLDESC B, TBLDESC C
     WHERE A.CODE_1 = B.CODE1
     AND  A.CODE_2 = (CASE WHEN a.CODE_2 IS NULL THEN '' ELSE C.CODE1 END);

You need to read up on joins (inner and outer). I'm also not entirely sure what you're doing with TBLDESC C, but this is my best guess. The left join means "show all columns from the left side, irrespective of whether they join to anything on the right".

SELECT ID, CODE_1, B.CODE_DESC, CODE_2, B.CODE_DESC
FROM TBLCODE AS A
LEFT JOIN TBLDESC AS B ON A.CODE_1 = B.CODE1

It looks like you want an inner join to the TBLDESC table for CODE_1 , as long as that is never null; and an outer join to the same table for CODE_2 . When CODE_2 is null that won't find anything, so C.CODE_DESC will be null - but making it an outer join means that the TBLCODE records won't be discarded, which is what you're seeing now from both being inner joins:

SELECT A.ID, A.CODE_1, B.CODE_DESC AS DESC_1, A.CODE_2, C.CODE_DESC AS DESC_2
FROM TBLCODE A
JOIN TBLDESC B ON B.CODE1 = A.CODE_1
LEFT JOIN TBLDESC C ON C.CODE1 = A.CODE_2;

If CODE_1 might be null then make them both LEFT JOIN .

If you don't want to hit the table twice you could use a single outer join and then CASE to decide which goes where, but it's a bit messy; for s small-ish look-up table it probably isn't worth it:

SELECT A.ID, A.CODE_1,
  MAX(CASE WHEN B.CODE1 = A.CODE_1 THEN B.CODE_DESC END) AS DESC_1,
  A.CODE_2,
  MAX(CASE WHEN B.CODE1 = A.CODE_2 THEN B.CODE_DESC END) AS DESC_2
FROM TBLCODE A
LEFT JOIN TBLDESC B ON B.CODE1 IN (A.CODE_1, A.CODE_2)
GROUP BY A.ID, A.CODE_1, A.CODE_2
ORDER BY A.ID;

SQL Fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM