我试图根据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会检索条件范围内的数据。问题是不止这三个状态。
答案 0 :(得分:3)
问题在于AND
和OR
子句的顺序。
尝试一下:
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'
)