简体   繁体   中英

SQL Joining tables and display second table as two columns based on data

I am wondering if it is possible to join two tables and show two columns based on the second table.

Example

I have two tables

ProductInfo table with the following data

ID  ProductID   ItemID
1   1           1
2   1           3
3   2           2
4   2           4
5   3           2
6   3           3

Items table

ID  Name    TYPE
1   Flour   1
2   Water   1
3   Yeast   2
4   Oats    2

I would like the output to be I would like the output to be this instead

ProductID  Name    Name
1          Flour   Yeast
2          Flour   Oats
3          Flour   Yeast

I have tried different joins like

SELECT ProductID, I1.Name, I2.Name
FROM ProductInfo
LEFT JOIN Items I1 ON I1.ID = ProductInfo.ItemID AND I1.TYPE = 1
LEFT JOIN Items I2 ON I2.ID = ProductInfo.ItemID AND I2.TYPE = 2

which results in this

在此处输入图像描述

Try the following, you can see demo here.

SELECT 
    ProductID, 
    max(I1.Name) as name1, 
    max(I2.Name) as name2
FROM ProductInfo
LEFT JOIN Items I1 ON I1.ID = ProductInfo.ItemID AND I1.TYPE = 1
LEFT JOIN Items I2 ON I2.ID = ProductInfo.ItemID AND I2.TYPE = 2
group by
    ProductId
order by
    ProductId

Output:

| productid | name1 | name2 |
| --------- | ----- | ----- |
| 1         | Flour | Yeast |
| 2         | Water | Oats  |
| 3         | Water | Yeast |

To split values to columns (pivot):

SELECT ProductID
     , CASE WHEN I.TYPE = 1 THEN I.Name END AS N1
     , CASE WHEN I.TYPE = 2 THEN I.Name END AS N2 
FROM ProductInfo P LEFT JOIN Items I ON I.ID = P.ItemID

With group by you must use Aggregate-Functions:

SELECT P.ProductID
     , min(CASE WHEN I.TYPE = 1 THEN I.Name END) AS N1
     , min(CASE WHEN I.TYPE = 2 THEN I.Name END) AS N2 
FROM ProductInfo P LEFT JOIN Items I ON I.ID = P.ItemID
GROUP BY P.ProductID

If your database support list_agg or group_concat you can make a concatination of all values from type 1 or 2. Than use this (eg. group_concat) than min.

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