查询返回的数据超出WHERE条件的范围

时间:2019-04-02 12:43:21

标签: sql sql-server ssms

我试图根据DateTime和状态从表中检索汇总数据。 问题是我需要多个状态值。 “其中1或2或3”

SELECT SUM(ticketTotalAmount)
FROM tickets 
WHERE ticketDate >= '2019/04/01 00:00:00' AND ticketDate <= '2019/04/02 23:59:59'
  AND ticketState = 'STAND BY'
   OR ticketState = 'WIN'
   OR ticketState = 'LOSE'

输出应基于这3种状态(赢,输或待机)以及ticketDate的范围来检索汇总数据,但实际输出超出了DateTime限制的范围。

删除状态条件并仅保留DateTime会检索条件范围内的数据。问题是不止这三个状态。

5 个答案:

答案 0 :(得分:3)

问题在于ANDOR子句的顺序。

尝试一下:

SELECT SUM(ticketTotalAmount)
FROM   tickets 
WHERE  ticketDate >= '2019/04/01 00:00:00' AND ticketDate <= '2019/04/02 23:59:59' AND
       (ticketState = 'STAND BY' OR ticketState = 'WIN' OR ticketState = 'LOSE');

甚至更好:

SELECT SUM(ticketTotalAmount)
FROM   tickets 
WHERE  ticketDate BETWEEN '2019/04/01 00:00:00' AND '2019/04/02 23:59:59'
  AND  ticketState IN ('STAND BY', 'WIN', 'LOSE');

答案 1 :(得分:1)

将票证状态条件放在圆括号内

SELECT SUM(ticketTotalAmount) FROM tickets 
WHERE ticketDate >= '2019/04/01 00:00:00' AND ticketDate <= '2019/04/02 23:59:59' AND ( ticketState = 'STAND BY' OR ticketState = 'WIN' OR ticketState = 'LOSE')

答案 2 :(得分:1)

使用IN

SELECT SUM(ticketTotalAmount) FROM tickets 
WHERE ticketDate >= '2019/04/01 00:00:00' AND ticketDate <= '2019/04/02 23:59:59' 
AND ticketState in( 'STAND BY' , 'WIN' ,'LOSE')

答案 3 :(得分:1)

我建议这样编写查询:

SELECT SUM(t.ticketTotalAmount)
FROM tickets t
WHERE t.ticketDate >= '2019-04-01' AND
      t.ticketDate < '2019-04-03' AND
      t.ticketState IN ('STAND BY', 'WIN', 'LOSE');

请注意查询的更改:

  • 使用OR代替IN。更清楚了。这样可以解决您的显式问题。
  • 简化了日期逻辑,因此您不必处理时间值(或一天中最后几毫秒内发生的值)。
  • 表别名是一个好主意;我通常认为它们对于只有一个表的查询是可选的。

答案 4 :(得分:1)

使用IN([...])更容易阅读,但是查看和理解使用括号对条件进行分组很有用,这样您就可以得到想要的结果。示例:

SELECT SUM(ticketTotalAmount)
FROM tickets 
WHERE
        ticketDate >= '2019/04/01 00:00:00'
    AND ticketDate <= '2019/04/02 23:59:59'
    AND 
    (
           ticketState = 'STAND BY'
        OR ticketState = 'WIN'
        OR ticketState = 'LOSE'
    )