【问题标题】:Implement "not in" to select with case实施“不在”以选择与案例
【发布时间】:2016-06-28 06:45:05
【问题描述】:

我有选择:

select col1,
   case
    when col2 = 'AB' then col3
    else cols2
   end as colX,
col4,sum(col5) from table 1
where....
group by col1,
case
when col2 = 'AB' then col3
else cols2
end, col4

如何在 where 添加类似:col2 not in ('AA','BB')?

我无法将 col2 添加到我的选择中,因为我的整个选择语句中有几个联接。

【问题讨论】:

  • where <conditions> and col2 not in ('AA','BB') 有什么问题?
  • 发布整个 SQL 查询
  • 当我没有在 col 2 中时......我收到错误:无效的列名

标签: sql sql-server sql-server-2008 case notin


【解决方案1】:

将新条件放在WHERE 子句中。此外,如果您切换到使用派生表,则不必编写 case 表达式两次。 (更容易无错误地编码,更容易阅读,更容易维护。)

select col1, colX, col4, sum(col5)
from
(
    select col1,
           case when col2 = 'AB' then col3
                else cols2
           end as colX,
           col4,
           col5
    from table1
    where...
      and col2 not in ('AA', 'BB')
) dt
group by col1, colX, col4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多