2012-09-22 48 views
1

我有我的表中的一些數據如下:在多列中選擇單列值?

ID  Name 
    2 219SUN_BV_Secure_Gateway.pdf 
    3 197FDD_BV_Secure_Gateway.pdf 
    5 225RQB_BV_Secure_Gateway.pdf 
    6 A_00025_Q1_2012.pdf   
    7 A_00025_Q2_2012.pdf   
    8 A_00025_Q3_2011.pdf   
    9 C_00025_Q3_2011_PostLLC.pdf 
10 B_00025_Q3_2011.pdf   

我希望將數據按以下要求獲取:

    在第一列
  • ,我想數據的名稱以
  • 開始
  • 在第二列,我想數據,其名稱與三B列
  • 開始,我想數據名稱以C開頭

我用這個查詢:

SELECT 
    CASE 
     WHEN DocumentFile LIKE 'A%' THEN DocumentFile 
    END as DocFile_A, 
    CASE 
     WHEN DocumentFile LIKE 'B%' THEN DocumentFile 
    END as DocFile_B, 
    CASE 
     WHEN DocumentFile LIKE 'C%' THEN DocumentFile 
    END as DocFile_C 
FROM 
    RFP_DocumentVault 

這將返回我下面的結果:

DocFile_A    DocFile_B   DocFile_C 
NULL   NULL    NULL 
NULL   NULL    NULL 
NULL   NULL    NULL 
A_00025_Q1_2012.pdf NULL    NULL 
A_00025_Q2_2012.pdf NULL    NULL 
A_00025_Q3_2011.pdf NULL    NULL 
NULL   NULL   C_00025_Q3_2011_Post Partners II, LLC.pdf 
NULL   B_00025_Q3_2011.pdf  NULL 

但我想結果如下:

DocFile_A   DocFile_B     DocFile_C 
A_00025_Q1_2012.pdf B_00025_Q3_2011.pdf  C_00025_Q3_2011_Post Partners II, LLC.pdf 
A_00025_Q2_2012.pdf NULL      NULL 
A_00025_Q3_2011.pdf NULL      NULL 

任何想法,我怎麼能做到這一點?

回答

6

同意@GolezTrol,這是應該也許在演講中得到解決。但是,如果你有絕對的把握,你需要做的是,在SQL,這裏是他們的解決方案替代:

WITH ranked AS (
    SELECT 
    DocumentFile, 
    grp = 'DocFile_' + LEFT(DocumentFile, 1), 
    rnk = ROW_NUMBER() OVER (
     PARTITION BY LEFT(DocumentFile, 1) 
     ORDER BY DocumentFile 
    ) 
    FROM RFP_DocumentVault 
) 
SELECT * 
FROM ranked 
PIVOT (
    MAX(DocumentFile) FOR grp IN (DocFile_A, DocFile_B, DocFile_C) 
) p 
; 

有一個現場演示at SQL Fiddle了。

+0

您也是如此,但我已經接受GolezTrol答案。你的答案也在工作......感謝你的迴應...... :) –

+1

不錯。我不太瞭解數據透視表。我想我應該瞭解他們。 :) – GolezTrol

3

奇怪的要求。在我看來,這是一個顯示問題,而不是查詢應該解決的問題,但可以。 我沒有SQL服務器在這裏,但嘗試這樣的事情:

select 
    DocFile_A, DocFile_B, DocFile_C 
from 
    (select 
     row_number() over (order by DocumentFile) as RowNum_A, 
     DocumentFile as DocFile_A 
    from 
     RFP_DocumentVault 
    where 
     DocumentFile like 'A%') A 
    full outer join 
    (select 
     row_number() over (order by DocumentFile) as RowNum_B, 
     DocumentFile as DocFile_B 
    from 
     RFP_DocumentVault 
    where 
     DocumentFile like 'B%') B on RowNum_B = RowNum_A 
    full outer join 
    (select 
     row_number() over (order by DocumentFile) as RowNum_C, 
     DocumentFile as DocFile_C 
    from 
     RFP_DocumentVault 
    where 
     DocumentFile like 'C%') C on RowNum_C = RowNum_A or RowNum_C = RowNum_B 
order by 
    RowNum_A, RowNum_B, RowNum_C 
+0

真的很感謝。它的工作..非常感謝。 –

+1

M對不起,但我認爲andriy-m的方式是更可靠 –

+1

我不知道可靠,但是是短一點。 Mine更好地兼容其他數據庫,但這不應該成爲不使用pivot功能的理由,除非您需要交叉兼容性的特殊情況。無論如何,我明白。 :'(;-) – GolezTrol