【问题标题】:SQL - where statement conditionsSQL - where 语句条件
【发布时间】:2018-03-21 19:50:42
【问题描述】:

以下是我的查询,我对 sql 比较陌生,所以我的理解不是最好的。我希望我的查询结果只给我我在“where”语句中指定的名称。在我的查询下面有 4 个活动名称、1 个团队名称和 1 个日期范围(3 个不同的列,4 个活动位于“名称”列中)。它必须符合所有这些条件。

我的查询一直有效,直到我在“where”语句中指定的第二个名称。

查询:

SELECT *

FROM databse1.dbo.table1

where team_name = 'CTM Tier 2'
        and date >= '2018-02-01' and date <= '2018-02-28'
        and name = 'Post Vet 460' 
        and name = 'Post Vet CA Complex'
        and name = 'Post Vet CA Standard'
        and name = 'Post Vet CAA'

查询一直运行良好,直到(并且 name = 'Post Vet 460'),但如果我将查询作为一个整体运行,它会给我空白结果。在这种情况下我应该使用 case when 语句吗,非常感谢所有建议和提示!

【问题讨论】:

  • where(和on)子句中使用case 表达式 通常是个坏主意。请改用and/or 结构。

标签: sql where case-when


【解决方案1】:

不能同时使用所有这些,所以使用 in 运算符

and name in ('Post Vet 460', 'Post Vet CA Complex', 'Post Vet CA Standard', 'Post Vet CAA')

【讨论】:

    【解决方案2】:

    我想你想要IN:

    select t1.*
    from databse1.dbo.table1 t1
    where team_name = 'CTM Tier 2' and
          date >= '2018-02-01' and date <= '2018-02-28' and
          name in ('Post Vet 460', 'Post Vet CA Complex', 'Post Vet CA Standard', 'Post Vet CAA');
    

    您的查询没有返回任何内容,因为name相同 行上不能有不同 值。

    您可能还需要like,具体取决于您的数据是什么样的:

    select t1.*
    from databse1.dbo.table1 t1
    where team_name = 'CTM Tier 2' and
          date >= '2018-02-01' and date <= '2018-02-28' and
          name like 'Post Vet %'
    

    【讨论】:

      【解决方案3】:

      现在试试这个查询! 您需要找到具有这些名称之一的任何行。因此需要使用 OR 条件。

      SELECT *
      
      FROM databse1.dbo.table1
      
      where team_name = 'CTM Tier 2'
              and date >= '2018-02-01' and date <= '2018-02-28'
              and 
              (   name = 'Post Vet 460' 
              or  name = 'Post Vet CA Complex'
              or  name = 'Post Vet CA Standard'
              or  name = 'Post Vet CAA'
              )
      

      【讨论】:

        【解决方案4】:

        您面临的问题是因为您使用的是AND 运算符。

        您应该改用OR 运算符。

        这是正确的实现:

        WHERE team_name = 'CTM Tier 2'
                AND date >= '2018-02-01' AND date <= '2018-02-28'
                AND name = 'Post Vet 460' 
                OR name = 'Post Vet CA Complex'
                OR name = 'Post Vet CA Standard'
                OR name = 'Post Vet CAA'
        

        正如其他人指出的,您也可以使用IN

        WHERE team_name = 'CTM Tier 2'
                AND date >= '2018-02-01' AND date <= '2018-02-28'
                AND name IN ('Post Vet 460', 'Post Vet CA Complex', 'Post Vet CA Standard', 'Post Vet CAA')
        

        如果您想了解更多关于IN 以及与ORhave a look here 的区别。

        【讨论】:

          猜你喜欢
          • 2022-01-14
          • 2013-03-08
          • 1970-01-01
          • 2011-05-28
          • 1970-01-01
          • 2011-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多