我可以使用名称来引用我想要的字段吗?

时间:2015-08-11 16:10:15

标签: sql sql-server

让我在这里详细说明。我对SQL不太满意。在下面的Query中,我提取代码名称。每个代码名称都是唯一的。例如,'87507'引用'电子'。运行查询时,是否可以用表中的名称替换实际数字?

Select Distinct CLM_CC9
From Impact.dbo.tbl_cld
Where CLM_CC9 in ('8203','34004','86754','87507',
'8759','8523','8526','8552','8761','8562','8778','8587','7588',
'8759','8790','8594','8796','8701','8607','8713','8616','8617',
'8718','8619','87620','8621','8764','7628','8629','7631','8632',
'833','8734','8635','8736','7637','8738','8639','7640','8641','896    08') 
order by CLM_CC9

试过这个......好运......

Select distinct CLM_CC9,
case when CLM_CC9 = '87507' then Electronics 
when CLM_CC9 = '86754' then Toys
end as names
From Impact.dbo.tbl_cld
Where CLM_CC9 in ('8203','34004','86754','87507',
'8759','8523','8526','8552','8761','8562','8778','8587','7588',
'8759','8790','8594','8796','8701','8607','8713','8616','8617',
'8718','8619','87620','8621','8764','7628','8629','7631','8632',
'833','8734','8635','8736','7637','8738','8639','7640','8641','896    08') 
 order by CLM_CC9

2 个答案:

答案 0 :(得分:0)

Select distinct CLM_CC9,
       case when CLM_CC9 = '87507' then Electronics 
            when CLM_CC9 = '86754' then something
            ... -- add more statements as needed.
       end as somename
From Impact.dbo.tbl_cld
Where CLM_CC9 in ('8203','34004','86754','87507',
'8759','8523','8526','8552','8761','8562','8778','8587','7588',
'8759','8790','8594','8796','8701','8607','8713','8616','8617',
'8718','8619','87620','8621','8764','7628','8629','7631','8632',
'833','8734','8635','8736','7637','8738','8639','7640','8641','896    08') 
 order by CLM_CC9

您可以使用case语句。或者,如果要反复查询,请构建一个查找表。

如果您在表格中有列,则可以这样做,

Select distinct namecolumn
From Impact.dbo.tbl_cld
Where CLM_CC9 in ('8203','34004','86754','87507',
'8759','8523','8526','8552','8761','8562','8778','8587','7588',
'8759','8790','8594','8796','8701','8607','8713','8616','8617',
'8718','8619','87620','8621','8764','7628','8629','7631','8632',
'833','8734','8635','8736','7637','8738','8639','7640','8641','896    08') 
order by CLM_CC9

还要确保消除in子句中的重复值。

答案 1 :(得分:0)

可能你想要这样的东西:

SELECT
CASE CLM_CC9
    WHEN '87507' THEN 'Electronics'
    [WHEN when_value THEN statements]
    ELSE statements
END