One-to-many query

偶尔善良 提交于 2021-01-05 07:18:45

问题


I have an hypothetical database as the image below were each plant can have a maximum of 4 colours.

I wish to be able to return my results in a format similar to the below.

If I run a standard query with Inner Join the results are duplicated were the plant has more than one colour. I have therefore tried running multiple separate queries were I first return the plant then a new query to return the colours. I then loop though colour result to produce the output I desire.

I assume there is a far for efficient way to achieve this?

I am trying to do this as a query and as a stored procedure so any pointers would be much appreciated.


回答1:


If you know there are a maximum of 4 colors, then you can use row_number() and conditional aggregation:

select plantname,
       max(case when seqnum = 1 then colorname end) as color_1,
       max(case when seqnum = 2 then colorname end) as color_2,
       max(case when seqnum = 3 then colorname end) as color_3,
       max(case when seqnum = 4 then colorname end) as color_4
from (select p.plantname, p.plantid, c.colorname,
             row_number() over (partition by p.plantid order by c.colorid) as seqnum
      from plants p join
           plantcolors pc
           on pc.plantid = p.plantid join
           colors c
           on pc.colorid = c.colorid
     ) pc
group by plantname, plantid;


来源:https://stackoverflow.com/questions/65073530/one-to-many-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!