-3

I want to get SUM values from a table between two dates but I have another filter also. I am getting syntax error and could not find what is wrong. This is the SQL sentence:

SUM(IF((date BETWEEN '2020-01-01 00:00:00' AND '2020-01-31 23:59:59') AND ql=1),total,0) AS t1q1,
SUM(IF((date BETWEEN '2020-01-01 00:00:00' AND '2020-01-31 23:59:59') AND ql=2),total,0) AS t1q2,
SUM(IF((date BETWEEN '2019-12-01 00:00:00' AND '2019-12-31 23:59:59') AND ql=1),total,0) AS t2q1,
SUM(IF((date BETWEEN '2019-12-01 00:00:00' AND '2019-12-31 23:59:59') AND ql=2),total,0) AS t2k2
FROM myTable 
GROUP BY productID
ORDER BY productID ASC

Arda Balkan
  • 1
  • 1
  • 4

1 Answers1

0
SELECT
SUM(case when date>='2020-01-01' and date<'2020-02-01' AND ql=1 then total else 0 end) t1q1,
SUM(case when date>='2020-01-01' and date<'2020-02-01' AND ql=2 then total else 0 end) t1q2,
SUM(case when date>='2019-12-01' and date<'2020-01-01' AND ql=1 then total else 0 end) t2q1,
SUM(case when date>='2019-12-01' and date<'2020-01-01' AND ql=2 then total else 0 end) t2q2
FROM myTable 
GROUP BY productID
ORDER BY productID ASC
juergen d
  • 201,996
  • 37
  • 293
  • 362