【问题标题】:Filter based on a values in all columns根据所有列中的值进行过滤
【发布时间】:2014-05-07 01:16:48
【问题描述】:

我想获取日期范围内的记录。他的查询应该只过滤 colA 或 ColB 或 ColC 中的值大于 0 且不等于 null 的情况。现在,如果我尝试这个查询,我会在所有列中得到 2012、2011 和 0 值的范围。任何帮助表示赞赏。谢谢你。我正在使用 sql 2008 查询:

select  ColA, ColC, ColB 
from tableA join 
     tableB on tableA.id = TableB.id
where ColA > 0 
   or ColB > 0 
   or ColC > 0 
  and tableB .Collection Date between 01-01-2013 and 12-31-2013

数据:

date range colA  colB   ColB
2/4/2013   402   88     null
5/4/2012   null  501    522
12/6/2013  110   550    null
12/20/2013 85    null   101
12/8/2013  null  null   null
6/17/2012  852   225    null
3/22/2013  null  null   null
3/2/2013   null  null   null

输出应该是-

date range  colA    colB    ColB
2/4/2013    402     88      null
12/6/2013   110     550     null
12/20/2013  85      null    101

【问题讨论】:

    标签: sql sql-server tsql


    【解决方案1】:

    尝试使用括号:

    select  ColA, ColC, ColB 
    from tableA join 
         tableB on tableA.id = TableB.id
    where (ColA > 0 or ColB > 0 or ColC > 0 )
       and tableB.[Collection Date] between 01-01-2013 and 12-31-2013
    

    使用COALESCE

    select  ColA, ColC, ColB 
    from tableA join 
         tableB on tableA.id = TableB.id
    where COALESCE(ColA,ColB,ColC) IS NOT NULL
       and tableB.[Collection Date] between 01-01-2013 and 12-31-2013
    

    【讨论】:

    • 啊……我错过了括号。谢谢@Raging Bull
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2021-08-01
    • 2021-12-29
    • 2021-06-23
    • 1970-01-01
    相关资源
    最近更新 更多