问题
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