2013-04-30 70 views
0

這裏是我的問題的一個示例表:要在多個列中檢索多行值轉換爲單列單個表

數據庫: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

請分享,如果你有一個這是很好的方法,需要你的幫助。

在此先感謝

+1

這種操作確實屬於您的應用程序的表示層。 – eggyal 2013-04-30 07:51:38

回答

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 

但是......這隻能是你有沒有更多的3所大學用相同的ID,如果你有更多的,你需要額外添加連接。

也看着你表結構我認爲你應該閱讀更多關於Database Normalization它可以幫助你。

你可以做這樣的事情:

enter image description here

+0

謝謝stephan ....你的代碼工作併爲我提供了所需的輸出。關於正常化,您認爲我的桌子應該如何構造,以適合我的要求。在這種情況下,我沒有超越2NF。因爲我指的是edutype是關鍵屬性的兩個表。 – pkg 2013-04-30 13:41:45

+0

np ...我爲數據添加了一個可能的結構 – Stephan 2013-04-30 14:14:06

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; 

但是,這是非常糟糕,unconsistent解決方案。在你的地方,我會嘗試重新組織對select的要求。也許你沒有提到你有這樣的輸出。

+0

其實,我需要這種輸出,以便我可以將它們導出到Excel表格中。 – pkg 2013-04-30 13:45:13

0

雖然以下形式的數據透視表查詢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;