我必须通过比较两个ID列中的数据来显示信息,一列有'ALL'而数字是ID,而另一列只有ID作为ID。我的问题是,我无法将字符和数字列与数字列进行比较。所以我正在使用CASE WHEN。
如果值为“ALL”,则在输出中显示“ALL”,否则显示匹配记录的名称。
以下是代码:
CASE
WHEN secorg.org_id = 'ALL' THEN 'ALL'
WHEN secorg.org_id = progmap.org_id THEN secorg.org_name
END AS org_name,
条件是:'secorg.org_id = progmap.org_id',它基于id,如果id相同,我必须显示secorg.org_name。
以下是整个查询:
SELECT distinct program_id,
prog_name,
case
when Eitc_Active_Switch = '1' then 'ON'
when Eitc_Active_Switch = '0'then 'OFF'
End as Prog_Status,
progmap.client_id,
case
when secorg.org_id = 'ALL' then 'ALL'
--when secorg.org_id = progmap.org_id then secorg.org_name
else secorg.org_name
end as org_name,
case
when prog.has_post_calc_screen = 'True' then 'True'
Else 'False'
End as Referal_ID,
case
when progmap.program_ID IN ( 'AMC1931', 'AMCABD', 'AMCMNMI',
'AMC' )
And sec.calwinexists_ind = '1' then 'Yes'
when progmap.program_ID IN ( 'AMC1931', 'AMCABD', 'AMCMNMI',
'AMC' )
And sec.calwinexists_ind = '0'then 'No'
when progmap.program_ID NOT IN (
'AMC1931', 'AMCABD', 'AMCMNMI', 'AMC' ) then
'N/A'
End as calwin_interface,
sec.Client_name
FROM ref_programs prog (nolock)
LEFT OUTER JOIN ref_county_program_map progmap (nolock)
ON progmap.program_id = prog.prog_id
AND progmap.CLIENT_ID = prog.CLIENT_ID
INNER join sec_clients sec (nolock)
on sec.client_id = progmap.Client_id
Inner join sec_organization secorg (nolock)
on secorg.org_id = progmap.org_id
答案 0 :(得分:1)
为什么不将数字列转换为varchar列?
如果你正在使用SQL SERVER,你可以这样做:
CONVERT(VARCHAR,secorg.org_id) = CONVERT(VARCHAR,progmap.org_id)
当'ALL'和数字的列都是'All'时,你必须对实例进行外连接,因为它不能内连接到另一个表。
对于基于上面代码的快速修复,您只需将第二个WHEN子句更改为如此(再次假设您使用的是MS SQL SERVER):
WHEN CONVERT(VARCHAR,secorg.org_id) = CONVERT(VARCHAR,progmap.org_id) THEN secorg.org_name
尝试将此作为您的查询:
SELECT DISTINCT
program_id,
prog_name,
CASE Eitc_Active_Switch
WHEN '1' THEN 'ON'
ELSE 'OFF'
END AS Prog_Status,
progmap.client_id,
ISNULL(secorg.org_name,'ALL') AS org_name,
CASE prog.has_post_calc_screen
WHEN 'True' THEN 'True'
ELSE 'False'
END AS Referal_ID,
CASE WHEN progmap.program_ID IN ('AMC1931','AMCABD','AMCMNMI','AMC') AND sec.calwinexists_ind = '1' THEN
'Yes'
WHEN progmap.program_ID IN ('AMC1931','AMCABD','AMCMNMI','AMC') AND sec.calwinexists_ind = '0' THEN
'No'
WHEN progmap.program_ID NOT IN ('AMC1931','AMCABD','AMCMNMI','AMC') THEN
'N/A'
END AS calwin_interface,
sec.Client_name
FROM
ref_programs prog (nolock)
LEFT OUTER JOIN ref_county_program_map progmap (nolock) ON progmap.program_id = prog.prog_id AND progmap.CLIENT_ID = prog.CLIENT_ID
INNER JOIN sec_clients sec (nolock) ON sec.client_id = progmap.Client_id
LEFT OUTER JOIN sec_organization secorg (nolock) ON CONVERT(VARCHAR,secorg.org_id) = CONVERT(VARCHAR,progmap.org_id)
答案 1 :(得分:1)
案例陈述很好,它的字段别名很糟糕
END As org_name
像secorg.org_name这样的多部分别名将不起作用