如果一个值存在则选择记录

时间:2018-07-12 15:30:02

标签: sql sql-server tsql

真的为此苦苦挣扎,我不知道为什么。我的桌子看起来像这样:

FundID    BenchmarkID    BenchmarkType  StartDate    EndDate
A         1              Primary        2018-06-01   NULL
A         2              Reporting 1    2018-06-01   NULL
B         1              Primary        2018-07-01   NULL
C         2              Primary        2018-06-01   NULL
C         1              Reporting 1    2018-06-01   NULL

我想做的是仅选择BenchmarkType为“ Reporting 1”的记录,但是如果没有Reporting 1记录,则选择“ Primary” BenchmarkType。我还需要将其用作连接其他表的一部分,并且它必须高效。

到目前为止,我的代码如下,并且我尝试过配合COALESCE,但是它不起作用,因为我说过我需要能够将此作为select的一部分,并可能在其他查询中用作加入:

SELECT * FROM Benchmark
WHERE BenchmarkType = COALESCE(CASE WHEN BenchmarkType = 'Reporting 1' OR BenchmarkType = 'Primary' THEN 'Reporting 1' ELSE NULL END,'Primary')
AND EndDate IS NULL

任何帮助将不胜感激。

谢谢

3 个答案:

答案 0 :(得分:2)

这是一个优先级查询。如果只有这两种类型可用,那么union all就足够简单了:

select b.*
from Benchmark b
where BenchmarkType = 'Reporting 1'
union all
select b.*
from Benchmark b
where BenchmarkType = 'Primary' and
      not exists (select 1 from Benchmark b2 where b2.fundId = b.fundId and b2.BenchmarkType = 'Reporting 1');

答案 1 :(得分:0)

为什么不将row_number()函数与top (1) with ties一起使用? :

select top (1) with ties b.*
from Benchmark b
order by row_number() over (partition by FundID 
                            order by (case when BenchmarkType = 'Reporting 1' 
                                           then 1 
                                           when BenchmarkType = 'Primary'
                                           then 2
                                      end)
                           );

答案 2 :(得分:0)

在一个选择查询中实现:

select *
from Funds a
where BenchmarkType = 'Reporting 1' 
OR 
 ( benchmarktype = 'Primary' and fundid not in (select fundid from funds where benchmarktype = 'Reporting 1'))
相关问题