我有一个表格如下,
Number Amount quantity
1 100 1
2 100 1
3 200 1
4 300 1
5 400 1
6 200 1
7 500 1
8 200 1
9 200 1
我有一个查询,
SELECT MIN(Number), MAX(number), SUM(quantity), amount
FROM table
WHERE condition
GROUP BY number, quantity, amount.
这回归,
Start End quantity amount
1 2 2 100
3 9 4 200
4 4 1 300
5 5 1 400
7 7 1 500
但我需要将结果设置为
Start End quantity amount
1 2 2 100
3 3 1 200
4 4 1 300
5 5 1 400
6 6 1 200
7 7 1 500
8 9 2 200
**如果我减去开始和结束然后它应该等于(数量-1)..
非常感谢任何帮助,
TIA。
请考虑这种情况,
Number Amount quantity
1 1000 1
2 1000 1
6 1000 1
8 1000 1
9 1000 1
预期结果集
Start End quantity amount
1 2 2 1000
6 6 1 1000
8 9 2 1000
TIA
答案 0 :(得分:1)
此查询现在还将介绍第二种情况,即投放块只有2个元素长。
select min(from_id), to_id, to_id - min(from_id) +1 AS quantity, amount from
(
select from_id, max(to_id) as to_id, amount from
(
select t1.id as from_id, t2.id as to_id, t1.amount
from foo t1
inner join foo t2 on t1.amount = t2.amount and t2.id >= t1.id
where not exists
(
select * from foo t3
where t3.ID > t1.ID
and t3.ID < t2.ID
and t3.amount != t1.amount
)
AND exists
(
select * from foo t3
where ((t3.ID = t1.ID
and t3.ID = t2.ID)
OR (t3.ID = t1.ID +1 AND
t3.ID = t2.ID))
and t3.amount = t1.amount
)
) x
group by from_id, amount
) y
group by to_id, amount
;
我从Oracle SQL for continuous grouping复制了基本方法并将其拼凑在一起:http://sqlfiddle.com/#!2/f4e0f/7/0