我的表如下所示,我想获得描述为"T02"的记录,否则返回null。
ID描述
D01 T01
DO1 T02
D_01 T03
C_02 T03
D_03 T01
D_03 T02
1D_03 T03
C_03 T04
预期结果
ID描述
D01 T02
D02 NULL
DO3 T02
我尝试过使用这个查询,但没有得到D02记录,它没有描述为T02的记录。
select ID, Description
where Description =
Case
when Description='T02' then Description
else NULL end
使用CASE和ROW_NUMBER函数尝试以下查询
create table #table1 (ID varchar(20), Description varchar(20))
insert into #table1 values
('D01' , 'T02')
,('D01' , 'T03')
,('D02' , 'T01')
,('D02' , 'T03')
,('D03' , 'T01')
,('D03' , 'T02')
,('D03' , 'T03')
,('D03' , 'T04')
select ID, Description from (
select a.ID, case when a.Description = 'T02' then 'T02' else null end as Description
, row_number()over(partition by a.id order by a.id, case when a.Description = 'T02' then 'T02' else null end desc) rno
from #table1 a
LEFT JOIN #table1 b on a.id =b.ID )a where rno=1
试试这个:
SELECT [ID]
,MAX(CASE [Description] = 'T02' THEN [Description] END) AS [Description]
FROM [my_table]
GROUP BY [ID];
使用以下格式并添加您的表名来代替<表名称>
SELECT
ID,
CASE
WHEN Description = 'T02' THEN Description
ELSE NULL
END AS ModifiedDescription
FROM <table_name>