[英]To retrieve values from multiple rows into a single row from a single table under multiple columns
这是我的问题的示例表:
数据库:MySQL 5.1
表名:教育
id edutype university subjects yearofpass percentmarks
200 1 CBSE Maths,Science,English,Hindi 2002 78.00
200 2 CBSE Maths,Physics,Chem,Biology 2004 68.00
200 3 WBUT Computer Science Engineering 2008 87.00
100 1 ICSE Maths,Science,English,Hindi 2001 72.00
100 2 CBSE Maths,Physics,Chem,Biology 2003 65.00
100 3 NIT Electronics Engineering 2008 75.00
300 1 CBSE Maths,Science,English,Hindi 2003 65.00
300 2 CBSE Maths,Physics,Chem,Biology 2005 63.00
300 3 VIT Metallurgy Engineering 2009 79.00
现在我想运行一个sql查询,它将以以下格式输出结果:
id uvr1 sub1 yop1 pcm1 uvr2 sub2 yop2 pcm2 uvr3 sub3 yop3 pcm3
200 CBSE Maths,Science,English,Hindi 2002 78.00 CBSE Maths,Physics,Chem,Biology 2004 68.00 WBUT Computer Science Engineering 2008 87.00
100 ICSE Maths,Science,English,Hindi 2001 72.00 CBSE Maths,Physics,Chem,Biology 2003 65.00 NIT Electronics Engineering 2008 75.00
300 CBSE Maths,Science,English,Hindi 2003 65.00 CBSE Maths,Physics,Chem,Biology 2005 63.00 VIT Metallurgy Engineering 2009 79.00
如果有什么好的方法可以实现这一点,请与我们分享,需要您的帮助。
提前致谢
您可以尝试使用CONCAT和SUBSTRING函数以及嵌套的SELECT。 喜欢:
SELECT SUBSTRING(CONCAT(subjects,
(
SELECT subjects FROM education WHERE university=CBSE and rownum=2
)),0,27)
FROM education WHERE university='CBSE' and rownum=1;
但这是非常糟糕且不一致的解决方案。 在您的位置,我将尝试重新组织选择的要求。 也许没有必要提到您提到的这样的输出。
您可以尝试以下方法:
SELECT
e1.id,
e1.university as uvr1,
e1.subjects as sub1,
e1.yearofpass as yop1,
e1.percentmarks as pcm1,
e2.university as uvr2,
e2.subjects as sub2,
e2.yearofpass as yop2,
e2.percentmarks as pcm2,
e3.university as uvr3,
e3.subjects as sub3,
e3.yearofpass as yop3,
e3.percentmarks as pcm3
FROM
Education as e1
LEFT JOIN Education as e2
ON e1.id = e2.id
AND e2.edutype = e1.edutype+1
LEFT JOIN Education as e3
ON e1.id = e3.id
AND e3.edutype = e1.edutype+2
WHERE
e1.edutype = 1
但是...这仅适用于您不再需要具有相同ID的3所大学,如果您需要更多,则需要添加额外的联接。
另外,在查看表结构时,我认为您应该阅读有关数据库标准化的更多信息,它可以为您提供帮助。
您可以执行以下操作:
虽然以下形式的PIVOT TABLE查询在MySQL中是完全可能的,但在大多数情况下,最好按照eggyal的建议进行并在应用程序级别处理此类事情。
SELECT id
, MAX(CASE WHEN edutype = 1 THEN university END) uvr1
, MAX(CASE WHEN edutype=1 THEN subjects END) sub1
FROM education
GROUP
BY id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.