Show TOP 1 considering where condition if present -SQL 查询

Show TOP 1 considering where condition if present -SQL query

我有一个案例,我正在使用如下 OUTER APPLY 查询

OUTER APPLY (
    SELECT TOP 1 CUSTOMER_CATEGORY 
    FROM   [UX_VW_CUSTOMER_DETAILS] UVFS
    WHERE  UVFS.CUSTOMER_ID = ss.CUSTOMER_ID
) SFD

但我有新的要求,如果存在 customer_category = 'General',应该考虑 OUTER APPLY

伪代码如下

if (Any Item present in [UX_VW_CUSTOMER_DETAILS] with CUSTOMER_CATEGORY=="General' for the specific customer)
{
    SELECT TOP 1 CUSTOMER_CATEGORY 
    FROM   [UX_VW_CUSTOMER_DETAILS] UVFS
    WHERE  UVFS.CUSTOMER_ID = ss.CUSTOMER_ID
    AND UVFS.CUSTOMER_CATEGORY LIKE '%General%'
}
ELSE
{
    SELECT TOP 1 CUSTOMER_CATEGORY 
    FROM   [UX_VW_CUSTOMER_DETAILS] UVFS
    WHERE  UVFS.CUSTOMER_ID = ss.CUSTOMER_ID
}

任何人都可以提出更好的方法来有效地重写外部应用代码。

您可以通过在 outer apply 查询中添加一个 order by 子句来组合您的条件,以确定 CUSTOMER_CATEGORY = 'General' 的优先级,例如

select top 1 CUSTOMER_CATEGORY
from [UX_VW_CUSTOMER_DETAILS] UVFS
where UVFS.CUSTOMER_ID = ss.CUSTOMER_ID
order by case when UVFS.CUSTOMER_CATEGORY like '%General%' then 1 else 0 end desc

CUSTOMER_CATEGORY like '%General%' 为 1 时 case 表达式的结果,否则为 0。然后我们 order by case 表达式的结果以降序方式,即从最高到最低。总之,这意味着如果 CUSTOMER_CATEGORY like '%General%' 它将 select selected 作为优先级。

要进一步了解其工作原理,请考虑由以下人员产生的结果:

declare @Id int = 1; -- Choose a Customer ID to test with

select *
    , case when UVFS.CUSTOMER_CATEGORY like '%General%' then 1 else 0 end desc OrderBy
from [UX_VW_CUSTOMER_DETAILS] UVFS
where UVFS.CUSTOMER_ID = @Id
order by case when UVFS.CUSTOMER_CATEGORY like '%General%' then 1 else 0 end desc