0

我有一个表格条目如下,,

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

** 如果我减去 start 和 end 那么它应该等于 (quantity-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

4

1 回答 1

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 复制了用于连续分组的基本方法,并在此处将其组合在一起:http ://sqlfiddle.com/#!2/f4e0f/7/0

于 2013-09-23T12:48:26.957 回答