简体   繁体   English

SQL 连接表并根据数据将第二个表显示为两列

[英]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 ProductInfo表,包含以下数据

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

Items table Items

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我希望 output 成为我希望 output 成为这个

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: 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:使用 group by 你必须使用 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.如果您的数据库支持 list_agg 或 group_concat,您可以连接类型 1 或 2 的所有值。比使用它(例如 group_concat)比使用最小值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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