[英]How do you create a sql query including multiple rows in one table as columns
I have 2 tables, students and contacts tables. 我有2个表,学生表和联系人表。 There can be no more than 3 contacts per student.
每个学生最多只能有3位联系人。
Students table:
ID, Name
123, John
456, Jane
Contacts table:
ID, CO, Name, Relation
123, C1, Jill, Mother
123, C2, Doug, Father
123, C3, Larry, Brother
456, C1, Luis, Father
456, C2, Jill, Mother
I want sql output to look like this: 我希望sql输出看起来像这样:
ID, Name, C1, C1name, C1rel, C2, C2name, C2rel, C3, C3name, C3rel
123, John, C1, Jill, Mother, C2, Doug, Father, C3, Larry, Brother
456, Jane, C1, Luis, Father, C2, Jill, Mother
This is for an export to upload to a third party vendor. 这是为了导出到上载到第三方供应商。 Thank you.
谢谢。
You can use a case statement or sub queries. 您可以使用case语句或子查询。
SELECT ID, Name,
(SELECT CO FROM Contacts c
WHERE s.ID = c.ID
AND c.CO = "C1") END AS C1,
(SELECT Name FROM Contacts c
WHERE s.ID = c.ID
AND c.CO = "C1") END AS C1name,
(SELECT Relation FROM Contacts c
WHERE s.ID = c.ID
AND c.CO = "C1") END AS C1rel
FROM Students s
And so on 等等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.