我有两张桌子:这是
方形小提琴(http://sqlfiddle.com/#!9/5a51734/5)
1) table:data_aoc
| aoc_id | aoc_name | aoc_type | client_id |
|------------------------------|-----------|
1 | MA01 | sensor_1 | 4 | 1 |
2 | MA02 | sensor_2 | 15 | 1 |2) table:data_log
| log_id | log_aoc_id | trans_type | trans_value | trans_date |
|-------------------------------------------------------------|
1 | x1a1 | MA01 | 0 | 90 | 2017-10-20 |
2 | afaf | MA01 | 0 | 90 | 2017-10-21 |
3 | va12 | MA02 | 0 | 10 | 2017-10-21 |
4 | gag2 | MA02 | 0 | 10 | 2017-11-25 |预期结果
Total value for MA02 should be 10 but it shows 20我的问题如下
SELECT
(CASE
WHEN a.aoc_type IN ('4')
THEN IFNULL((SUM(b.trans_value * case b.trans_type when '0' then -1 else 1 end)),0)
WHEN a.aoc_type IN ('15')
THEN IFNULL((SUM(b.trans_value * case when b.trans_type='0' AND DATE(b.trans_date) <= DATE(NOW()) then -1 else 1 end)),0)
END) as total
FROM data_aoc a
LEFT JOIN data_log b ON b.log_aoc_id = a.aoc_id
WHERE a.client_id='1'
GROUP BY a.aoc_name
ORDER BY a.aoc_id asc当aoc_type为(15)时,它将在日期条件内求和该值。
DATE(b.trans_date) <= DATE(NOW())但是,当我执行查询时,它不会在日期条件下产生结果。*一些时间戳是在现在()日期之后提前生成的。
预期的结果应该是:
| Total |
|-------|
| -180 |
| 10 |但我得到
| Total |
|-------|
| -180 |
| 0 | <----- it should be 10 because of the date condition i put谢谢!
发布于 2017-11-01 01:04:57
作为对唐同样发现的跟进,以及你对“不算数”的澄清,我想出了一个问题.先对日期进行预检查,然后再乘以零,否则,应用+/- 1因子。
SELECT
SUM( b.trans_value *
CASE when ( a.aoc_type = '15'
AND b.trans_type = '0'
AND DATE(b.trans_date) > DATE(NOW()) )
then 0
when ( a.aoc_type = '4'
AND b.trans_type = '0' )
OR ( a.aoc_type = '15'
AND b.trans_type = '0'
AND DATE(b.trans_date) <= DATE(NOW()) )
then -1 else 1 end ) as total
FROM
data_aoc a
LEFT JOIN data_log b
ON a.aoc_id = b.log_aoc_id
WHERE
a.client_id='1'
GROUP BY
a.aoc_name
ORDER BY
a.aoc_id asc也在上发布
发布于 2017-11-01 00:32:06
它似乎运作得恰如其分。关于日期条款,我得到:
Sensor 1 = -180
Sensor 2 = 0如果分解求和,将得到两行数据,分别用于传感器2、10和11-25 (在日期限制之前,所以它乘以-1)和10行(在日期限制之后,它被乘以1)。
10 * -1 + 10 * 1 = 0传感器#2读数正确。
我不明白你为什么认为它应该是其他的东西。
https://stackoverflow.com/questions/47040823
复制相似问题