我有以下数据:
id customer date value1 value2 isTrue
10 13 2013-08-20 00:00:00.0000 170 180680 0
11 13 2013-09-02 00:00:00.0000 190 181830 0
12 13 2013-09-07 00:00:00.0000 150 183000 1
13 13 2013-09-14 00:00:00.0000 150 183930 0
14 13 2013-09-16 00:00:00.0000 150 184830 0
15 13 2013-09-19 00:00:00.0000 150 185765 1
16 13 2013-09-30 00:00:00.0000 800 187080 0
17 13 2013-10-02 00:00:00.0000 100 188210 0
28 13 2013-10-04 00:00:00.0000 380 188250 1
我如何得到以下结果,其中SumValue1是value1的总和,直到字段isTrue得到True并且重置之后,每当IsTrue字段变为True时,差值Value2是字段值2的差异?
id customer date value1 value2 isTrue SumValue1 DifferenceValue2
10 13 2013-08-20 00:00:00.0000 170 180680 0
11 13 2013-09-02 00:00:00.0000 190 181830 0
12 13 2013-09-07 00:00:00.0000 150 183000 1 510 2320
13 13 2013-09-14 00:00:00.0000 150 183930 0
14 13 2013-09-16 00:00:00.0000 150 184830 0
15 13 2013-09-19 00:00:00.0000 150 185765 1 450 2765
16 13 2013-09-30 00:00:00.0000 800 187080 0
17 13 2013-10-02 00:00:00.0000 100 188210 0
28 13 2013-10-04 00:00:00.0000 380 188250 1 1280 2485
答案 0 :(得分:0)
假设id
排序,此查询将执行:
SELECT
id, customer, date, value1, value2, isTrue,
CASE isTrue WHEN 1 THEN (SELECT TOTAL(value1) FROM t WHERE customer=t2.customer AND id>t2.prev_id AND id<=t2.id) END AS SumValue1,
CASE isTrue WHEN 1 THEN value2-(SELECT value2 FROM t WHERE customer=t2.customer AND id=t2.prev_id) END AS DifferenceValue2
FROM (SELECT *, CASE isTrue WHEN 1 THEN COALESCE((SELECT id FROM t AS _ WHERE customer=t.customer AND date<t.date AND isTrue ORDER BY date DESC LIMIT 1), -1) END AS prev_id FROM t) AS t2;
一步一步:
上一个id
其中isTrue
由:
SELECT id FROM t AS _ WHERE customer=t.customer AND date<t.date AND isTrue ORDER BY date DESC LIMIT 1
使用COALESCE(..., -1)
将确保在所有其他人id
之前获得非空-1
。
SELECT *, CASE isTrue WHEN 1 THEN ... END AS prev_id FROM t
将返回t
中添加了列prev_id
的所有行。
最后,在之前的结果中查询SELECT TOTAL(value1) FROM t WHERE customer=t2.customer AND id>t2.prev_id AND id<=t2.id
和value2-(SELECT value2 FROM t WHERE customer=t2.customer AND id=t2.prev_id
将返回所需的结果。