简体   繁体   中英

Join multiple rows from Table 2 into separate columns when selecting data based on ID linked to table 1?

I may have the incorrect database design, but I have an issue as follows:

    +-----------+        +------------+-----------+
    |  table1   |        |         table2         |
    +-----------+        +------------+-----------+
    | Type      |        | Type       | Item      |
    | Fruit     |        | Fruit      | Apple     |
    | Vegetable |        | Fruit      | Orange    |
    +-----------+        | Fruit      | Pear      |
                         | Vegetable  | Zucchini  |
                         +------------+-----------+

I would like to query my DB to return something that looks like this:

+-------------+----------+----------+---------+
|     Result  |          |          |         |
+-------------+----------+----------+---------+
| Type        | Result1  | Result2  | Result3 |
| Fruit       | Apple    | Orange   | Pear    |
+-------------+----------+----------+---------+

When I query items based on the "Fruit" ID. My current query will return a row for each, but I'd like to turn these rows into separate columns in the results table.

I've looked around into using different types of joins and group_concat, but I don't think any of these are explicitly appropriate as a solution by itself. I'm a bit of an SQL rookie so I'm having trouble on knowing "what" to look for.

SELECT t1.Type, t2.item,
FROM table1 as t1, table2 as t2
WHERE t2.Type="Fruit";  

I understand that this will return each iteration of the results, but is not what I want.

You can use conditional aggregation:

select type,
       max(case when seqnum = 1 then item end) as item_1,
       max(case when seqnum = 2 then item end) as item_2,
       max(case when seqnum = 3 then item end) as item_3
from (select t2.*, row_number() over (partition by type order by type) as seqnum
      from table2 t2
     ) t2
where type = 'Fruit'
group by type;

Note that table1 is not needed because type is in table2 .

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