MySQL,多行分隔字段
我有一个 MySQL 表,其中包含如下字段和数据;
PartNumber Priority SupName
a1 0 One
a2 0 One
a2 1 Two
a3 0 One
a4 1 Two
a5 2 Three
我正在尝试创建一个视图,其中具有多行的部分组合成一行,并组合成单独的字段,例如
Ideally This;
PartNumber Sup1 Sup2 Sup3
a1 One NULL NULL
a2 One Two NULL
a3 One NULL NULL
a4 Two NULL NULL
a5 Three NULL NULL
或者我可以接受这个
PartNumber Sup1 Sup2 Sup3
a1 One NULL NULL
a2 One Two NULL
a3 One NULL NULL
a4 NULL Two NULL
a5 NULL NULL Three
我将如何构建视图或选择语句来完成此任务?
到目前为止我最接近的是;
SELECT PartNumber,
IF(Priority=0, SupName, NULL) AS Sup1,
IF(Priority=1, SupName, NULL) AS Sup2,
IF(Priority=2, SupName, NULL) AS Sup3
FROM SupXref
ORDER BY PartNumber
然而,这为每个字段提供了单独的行,并且我需要一行。
I have a MySQL table with fields and data such as follows;
PartNumber Priority SupName
a1 0 One
a2 0 One
a2 1 Two
a3 0 One
a4 1 Two
a5 2 Three
I am trying to create a view where the parts that have multiple rows are combined into a single row, and into separate fields such as
Ideally This;
PartNumber Sup1 Sup2 Sup3
a1 One NULL NULL
a2 One Two NULL
a3 One NULL NULL
a4 Two NULL NULL
a5 Three NULL NULL
Or I can live with this
PartNumber Sup1 Sup2 Sup3
a1 One NULL NULL
a2 One Two NULL
a3 One NULL NULL
a4 NULL Two NULL
a5 NULL NULL Three
How would I build a view or select statement to accomplish this?
The closest I have come so far is;
SELECT PartNumber,
IF(Priority=0, SupName, NULL) AS Sup1,
IF(Priority=1, SupName, NULL) AS Sup2,
IF(Priority=2, SupName, NULL) AS Sup3
FROM SupXref
ORDER BY PartNumber
This however gives me a separate row for each of the fields and I need a single line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只是错过了一个分组:)
编辑:
玩了一段时间后,我想我得到了您正在寻找的第一个解决方案。尝试一下:)
对于下表:
数据变成这样:
最后变成这样:
You're just missing a group by :)
Edit:
After playing for a while I think I got the first solution you're looking for. Give it a try :)
For the following table:
Data is turn into this:
And finally into this: