0

我有一个使用OUTER APPLY如下查询的情况

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

但是我有新的要求,如果存在的话,OUTER APPLY应该在哪里发生。customer_category = 'General'

伪代码如下

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
}

任何人都可以建议以有效方式重写外部应用代码的更好方法。

4

1 回答 1

3

您可以通过在查询中添加 order by 子句来组合您的条件outer apply来确定优先级,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

case 表达式的结果 whenCUSTOMER_CATEGORY like '%General%'为 1,否则为 0。然后我们order by以降序的方式表达case的结果,即从高到低。总之,这意味着如果CUSTOMER_CATEGORY like '%General%'它将选择 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
于 2020-05-21T03:32:01.817 回答