AB *_*yas 1 sql sql-server sql-server-2005 sql-server-2008
我的表格中有一些数据如下:
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
Run Code Online (Sandbox Code Playgroud)
我想按照以下要求获取数据:
我用过这个查询:
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
Run Code Online (Sandbox Code Playgroud)
这会返回以下结果:
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
Run Code Online (Sandbox Code Playgroud)
但我想要的结果如下:
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
Run Code Online (Sandbox Code Playgroud)
知道我怎么能这样做吗?
同意@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
;
Run Code Online (Sandbox Code Playgroud)
还有SQL Fiddle的现场演示.