简体   繁体   中英

Returning null instead of empty rows for a particular column in an SQL query

We have a Table which is really a 2D array where each (Row, Column) represents a particular piece of data, for example (1,4) might represent the Location and (2,4) might represent the Price of pizza.

For a particular Person, they will have exactly one entry for each (Row, Column). Sometimes this data might need translation, for example Location might be stored as L for London and M for Manchester. We then have a separate table called Location mapping which translate L to London and M to Manchester. Sometimes we don't need any translation, for example the price can just be returned as-is.

In effect, what I am hoping to do is to find some SQL to convert this 2D Array into a 1-row output:

Original Table:

 RowNo | C1 | C2
 ------+----+-----
 R1    | L  | 2.0
 R2    | 50 | J

So:

(1,1) represent location,
(1,2) represents price of pizza
(2,1) represnts age
(2,2) represents Initials

Only location needs to be translated.

What I would like is to get back:

 Location | PriceOfPizza | Age | Initials
 ---------+--------------+-----+---------
 London   |     2.0      | 50  |    J

Now if L does not exist in the LocationTranslation table, I still want to return the row but with just a blank value (or null) under the Location column.

Please could anyone help?

Thanks, Wing

I have a very limited knowledge of DB2, but I believe the following should work for almost all RDMS

select 
c.Location as "Location", 
b.C2 as 'PriceOfPizza' 
FROM from DataTable a 
INNER JOIN DataTable b ON (b.RowNo = 'R2') 
LEFT JOIN LocationTranslation c  ON (c.RawLocation = a.C1)
WHERE a.RowNo = 'R1' 
select c.Location as "Location", b.C2 as 'PriceOfPizza' 
from DataTable a
inner join DataTable b on a.RowNo = 'R1' and b.RowNo = 'R2'
left outer join LocationTranslation c on a.RowNo = 'R1' and c.RawLocation = a.C1

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