我正在尝试按字母顺序排列每个组合将单元格合并在一起。即每个可能对的一行,一组3,一组4等等。
可能有帮助的信息;每个ID都有2到6个部分,并说明ID有多少部分。
即。我的数据目前看起来像这样;
ID | Number_of_parts | Part_no. | Description | Price
1 3 1 Apple 0.50
1 3 2 Cucumber 0.25
1 3 3 Banana 0.30
2 2 1 Donut 1.00
2 2 2 Banana 0.40
我希望得到以下结果;
ID | Desc1 | Price1 | Desc2 | Price2 | Desc3 | Price3 | Desc4 | Price4
1 Apple 0.50 Banana 0.30 Cucumber 0.25 NULL NULL
1 Apple 0.50 Banana 0.30 NULL NULL NULL NULL
1 Apple 0.50 Cucumber 0.25 NULL NULL NULL NULL
1 Banana 0.30 Cucumber 0.25 NULL NULL NULL NULL
2 Banana 0.40 Donut 1.00 NULL NULL NULL NULL
感谢任何帮助,
感谢。
答案 0 :(得分:1)
如果您被限制为四种可能性,则可以使用left join
。以下几乎可行:
select d1.id,
d1.desc as desc1, d1.price as price1,
d2.desc as desc2, d2.price as price2,
d3.desc as desc3, d3.price as price3,
d4.desc as desc4, d4.price as price4
from data d1 left join
data d2
on d1.id = d2.id and d1.partno < d2.partno left join
data d3
on d1.id = d3.id and d2.partno < d3.partno left join
data d4
on d1.id = d4.id and d3.partno < d4.partno;
问题是它不会给苹果/香蕉。所以,你似乎想要至少成对。然后我认为最简单的方法是使用UNION
:
select d1.id,
d1.desc as desc1, d1.price as price1,
d2.desc as desc2, d2.price as price2,
d3.desc as desc3, d3.price as price3,
d4.desc as desc4, d4.price as price4
from data d1 join
data d2
on d1.id = d2.id and d1.partno < d2.partno left join
data d3
on d1.id = d3.id and d2.partno < d3.partno left join
data d4
on d1.id = d4.id and d3.partno < d4.partno;
union
select d1.id,
d1.desc as desc1, d1.price as price1,
d2.desc as desc2, d2.price as price2,
NULL, NULL, NULL, NULL
d3.desc as desc3, d3.price as price3,
d4.desc as desc4, d4.price as price4
from data d1 join
data d2
on d1.id = d2.id and d1.partno < d2.partno;