SQL CASE中的多个属性

时间:2016-10-10 09:21:47

标签: sql sql-server

我有一个SQL查询,它将比较web_pub_subfile表中的file_names,如果找到文件则显示信息

SELECT file_name, CASE WHEN EXISTS(SELECT 1
           FROM  web_pub_subfile  t JOIN infocard_1 ic on ic.info_card_id=t.info_card_id
           WHERE  E.file_name = t.file_name and lower(ic.vault_name) ='SU-SPEC-RELEASE') 
           THEN 'YES'
           ELSE 'NO' END AS File_Found
FROM (VALUES 
('00924.dwg'),
('00960.dwg'),
('00973.dwg'),
('00984.dwg'),
('01008.dwg')) E(file_name)

我将以这种格式获得OUTPUT

file_name   File_Found
----------------------
00924.dwg   NO
00960.dwg   YES
00973.dwg   YES
00984.dwg   YES
01008.dwg   YES

我可以从TABLE中显示另外两个属性(document_num和vault_name) - > web_pub_subfile使用ABOVE Query?

file_name   File_Found  document_num  vault
-----------------------------------------------------
00924.dwg   NO          Test1         SU-SPEC-RELEASE
00960.dwg   YES         Test2         SU-SPEC-RELEASE
00973.dwg   YES         Test3         SU-SPEC-RELEASE
00984.dwg   YES         Test4         SU-SPEC-RELEASE
01008.dwg   YES         Test5         SU-SPEC-RELEASE

1 个答案:

答案 0 :(得分:0)

CASE语句不能返回多个列

您可以将sub-query移至left join

SELECT file_name,
       CASE
         WHEN t.file_name IS NOT NULL THEN 'YES'
         ELSE 'NO'
       END AS File_Found,
       document_num, -- Replace it with the original column name 
       vault_name    -- Replace it with the original column name 
FROM   (VALUES ('00924.dwg'),
               ('00960.dwg'),
               ('00973.dwg'),
               ('00984.dwg'),
               ('01008.dwg')) E(file_name)
       LEFT JOIN web_pub_subfile t
              ON E.file_name = t.file_name
       LEFT JOIN infocard_1 ic
              ON ic.info_card_id = t.info_card_id
                 AND Lower(ic.vault_name) = 'SU-SPEC-RELEASE'