2016-03-11 63 views
1

賦值我有一個這樣的表:添加新列,並從現有表

REFERENCE  FILE    FILESIZE HEADING 
-------------------------------------------------- 
ref001  abc123.zip  0    
ref001  def123.sgm  46661  pdf 
ref001  ghi123.xml  1159  xml 
ref001  jkl456.zip  0   
ref001  mno456.sgm  22852  rtf 
ref001  pqr456.xml  1181  xml 
ref001  stu789.zip  0 
ref001  vwx789.sgm  5959  pdf 
ref001  yza789.xml  1162  xml 

基礎上,FILESIZE AND HEADING COLUMN從上面我怎樣才能創建新列?像這樣:

FILE    PDF   RTF  XML 
-------------------------------------------- 
abc123.zip  0   0   0 
def123.sgm  46661  0   0 
ghi123.xml  0   0   1159 
jkl456.zip  0   0   0 
mno456.sgm  0   22852  0 
pqr456.xml  0   0   1181 
stu789.zip  0   0   0 
vwx789.sgm  5959  0   0 
yza789.xml  0   0   1162 

感謝您的幫助! ☺

回答

1

你可以使用PIVOT

SELECT [File], 
     COALESCE([PDF],0) AS [PDF], 
     COALESCE([XML],0) AS [XML], 
     COALESCE([RTF],0) AS [RTF] 
FROM #tab 
PIVOT 
(
    MAX(FILESIZE) FOR HEADING IN ([PDF],[XML],[RTF]) 
) AS pvt 

LiveDemo

或簡單CASE

SELECT [File], 
     [XML] = CASE WHEN Heading = 'xml' THEN FileSize ELSE 0 END, 
     [PDF] = CASE WHEN Heading = 'pdf' THEN FileSize ELSE 0 END, 
     [RTF] = CASE WHEN Heading = 'rtf' THEN FileSize ELSE 0 END 
FROM #tab 

LiveDemo2

+0

哇。我是sql中的新手。謝謝!還有一件事,如果我的** HEADING COLUMN **不包含** rtf **,那麼不應該顯示RTF COLUMN – 404notfound

+0

@ 404notfound那麼您可能需要動態SQL。如果你是新手,我會堅持使用這個解決方案,並忽略'RTF'(全零)或者只是使用'SELECT [File],[XML],[PDF] FROM ...' – lad2025