以下是我的问题的示例表:
数据库: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
如果您有任何好的方法可以分享,需要您的帮助。
先谢谢
答案 0 :(得分:0)
您将尝试使用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;
但这是非常糟糕和不确定的解决方案。在你的位置,我会尝试重新组织选择的要求。也许你提到这样的输出并不是必须的。
答案 1 :(得分:0)
你可以试试这个:
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所大学。
另外看着你的表格结构我认为你应该阅读更多关于Database Normalization它可以帮助你的信息。
您可以这样做:
答案 2 :(得分:0)
虽然在MySQL中完全可以使用以下形式的PIVOT TABLE查询,但在大多数情况下,像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;