【问题标题】:SQL Server- SQL to write nested case in select statement or in where-on clause?SQL Server- SQL 在 select 语句或 where-on 子句中编写嵌套案例?
【发布时间】:2018-07-14 20:28:07
【问题描述】:

SQL 查询

select 
    case 
       when t2.property = 'TEST_1' and
            (t3.ltype like case when t3.lvalue=t1.DMetd and t3.ltype not in ('STATE','CITY') then t3.ltype end) 
          then t3.ltext 
          else null 
    end as myMethod
from  
    table1 t1 
join
    table2 t2 on t1.wid = t2.w_id 
left join
    tabl3 t3 on t3.lvalue = t2.mymethod  

我的CASE声明:

(t3.ltype like case when t3.lvalue=t1.DMetd and t3.ltype not in ('STATE','CITY') then t3.ltype end

在我的查询中,我应该在 select 子句中,还是在 where 或 on 子句中写 case 语句?

样本数据:

在 table3 我有这样的列

ltext, lvalue, ltype, care, cr, method1, effective care, cr, newmethod, 
urgent, UR, newmethod

我需要选择行

effective care, cr, newmethod

我需要忽略行

care, cr, method1

table2 我需要先检查

ON (t3.lvalue = t2.mymethod)  

t2 的列 mymethod 具有 CR、AR、UR 等值

table1 - 列 Dmethd 的值类似于 CR、AR、UR

【问题讨论】:

标签: sql plsql sql-server-2012 case sql-server-2016


【解决方案1】:

我的答案是,这取决于在语义上更能代表您正在建模的概念现实。

如果需要对返回的列进行操作以返回使用各种函数从基础数据制定的值,则将 case 语句放在 SELECT 中。但是,如果 CASE 语句用作过滤记录的数据选择过程的一部分,则将 CASE 语句放在那里。如果 CASE 语句有助于定义表如何关联在一起,则将它们放在 JOIN 语句中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多