Sql 如果某个值存在,请选择“记录”另一个值

Sql 如果某个值存在,请选择“记录”另一个值,sql,sql-server,tsql,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

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

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
我想做的是只选择基准类型为“Reporting 1”的记录,但如果没有基准类型为“Reporting 1”的记录,则选择“Primary”基准类型。我还需要将其用作连接到其他表的一部分,并且它需要高效

到目前为止,我的代码如下所示,我曾尝试巧妙地使用COALESCE,但它不起作用,正如我所说,我需要能够将其用作select的一部分,并可能在其他查询中用作join:

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
任何帮助都将不胜感激


谢谢

这是一个优先级查询。如果只有这两种类型可用,那么
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');

为什么不将
row_number()
函数与带领带的
top(1)一起使用呢

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)
                           );

在一个select查询中实现:

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

我认为
b.FundID=b2.FundID将在
存在的
中需要,但它不是100%清楚。@AaronDietz。非常感谢。你说得很对。抢手货