2011-12-24 31 views
2

指導如果解決方案可行。MySql表按分割字符串的值排序

enter image description here

我需要表如下結果

RAJ1 RAJ2 ARUN MUTHU 
----------------------- 
86  74 45 null 
74  86 45 null 
null 74 45 86 

我不知道從哪裏開始通過對程序或通過正常的查詢來實現這一點。

+1

將每個列聯合成一個長列表,將名稱,值拆分爲2列,然後在名稱上進行轉義。由於字符串操作,性能會很慢,但是當我們有非規格化數據時會發生這種情況。 – xQbert 2011-12-24 12:42:24

回答

1
SELECT 
    COALESCE(
    IF(LEFT(subj1,4)='RAJ1', SUBSTRING(subj1,6), NULL), 
    IF(LEFT(subj2,4)='RAJ1', SUBSTRING(subj2,6), NULL), 
    IF(LEFT(subj3,4)='RAJ1', SUBSTRING(subj3,6), NULL)) as RAJ1, 
    COALESCE(
    IF(LEFT(subj1,4)='RAJ2', SUBSTRING(subj1,6), NULL), 
    IF(LEFT(subj2,4)='RAJ2', SUBSTRING(subj2,6), NULL), 
    IF(LEFT(subj3,4)='RAJ2', SUBSTRING(subj3,6), NULL)) as RAJ2, 
    COALESCE(
    IF(LEFT(subj1,4)='ARUN', SUBSTRING(subj1,6), NULL), 
    IF(LEFT(subj2,4)='ARUN', SUBSTRING(subj2,6), NULL), 
    IF(LEFT(subj3,4)='ARUN', SUBSTRING(subj3,6), NULL)) as ARUN, 
    COALESCE(
    IF(LEFT(subj1,5)='MUTHU', SUBSTRING(subj1,7), NULL), 
    IF(LEFT(subj2,5)='MUTHU', SUBSTRING(subj2,7), NULL), 
    IF(LEFT(subj3,5)='MUTHU', SUBSTRING(subj3,7), NULL)) as MUTHU 
FROM thetable;