在ca时获得两行而不是一行

时间:2015-09-03 04:38:47

标签: sql-server case-when

示例:

--table for illustration--
create table #temp (dd int, typeId int, cl smallint)
insert into #temp (dd, typeId, cl)
values (1,681,75)
insert into #temp (dd, typeId, cl)
values (1,815,75)
insert into #temp (dd, typeId, cl)
values (2,681,75)
insert into #temp (dd, typeId, cl)
values (2,815,75)
insert into #temp (dd, typeId, cl)
values (3,681,75)
insert into #temp (dd, typeId, cl)
values (3,681,100)
insert into #temp (dd, typeId, cl)
values (4,681,75)

我正在寻找的查询应该带有唯一的dd(第一列)

select distinct dd, case when typeId = 681 then 'True'
end as BDFlagStatus,
case when typeId = 815 then 'True' 
end as ODFlagStatus
from #temp

resut是......

dd  BDFlagStatus    ODFlagStatus
1   NULL    TRUE
1   TRUE    NULL
2   NULL    TRUE
2   TRUE    NULL
3   TRUE    NULL
4   TRUE    NULL

我正在寻找......

dd  BDFlagStatus    ODFlagStatus
1   TRUE    TRUE
2   TRUE    TRUE
3   TRUE    NULL
4   TRUE    NULL

2 个答案:

答案 0 :(得分:1)

试试这个。 SQLFIDDLE演示

    SELECT   dd
    ,MAX(CASE 
        WHEN typeId = 681
            THEN 'True'

        END) AS BDFlagStatus
    ,MAX(CASE 
    WHEN typeId = 815
            THEN 'True'
        END) AS ODFlagStatus
FROM #temp
group by dd

答案 1 :(得分:0)

尝试:

;with cte
as
(
select distinct dd, case when typeId = 681 then 'True'
end as BDFlagStatus,
case when typeId = 815 then 'True' 
end as ODFlagStatus
from temp
  )
  select dd,max(BDFlagStatus),Max(ODFlagStatus)
  from cte group by dd

Fiddle Demo