在PostgreSQL中获取MIN()和MAX()而不是相关值

时间:2018-01-24 14:24:09

标签: sql postgresql

我有一个问题,我无法找到解决方案。这是我的情景:

parent_id | transaction_code | way_to_pay | type_of_receipt | unit_price | period | series | number_from | number_to | total_numbers
10        | 2444             |  cash      |   local         | 15.000     |  2018  |   A    |   19988     |    26010  | 10

分组parent_id, transaccion_code, way_to_pay, type_of_receipt, unit_price, periodo, series, MIN(number), MAX(number) and COUNT(number)时的结果。但分组隐藏数字并不相关,因为这是我孩子的情况:

parent_id | child_id | number 
10        |   1      | 19988 
10        |   2      | 19989
10        |   3      | 19990
10        |   4      | 19991
10        |   5      | 22001
10        |   6      | 22002
10        |   7      | 26007
10        |   8      | 26008
10        |   9      | 26009
10        |   10     | 26010

实现以下目标的神奇SQL是什么?

parent_id | transaction_code | way_to_pay | type_of_receipt | unit_price | period | series | number_from | number_to | total_numbers
10        | 2444             |  cash      |   local         | 15.000     |  2018  |   A    |   19988     |    19991  | 4
10        | 2444             |  cash      |   local         | 15.000     |  2018  |   A    |   22001     |    22002  | 2
10        | 2444             |  cash      |   local         | 15.000     |  2018  |   A    |   26007     |    26010  | 4

1 个答案:

答案 0 :(得分:0)

您可以通过减去序列来识别相邻的数字。如果你展示了你的查询会有所帮助,但想法是这样的:

select parent_id, transaccion_code, way_to_pay, type_of_receipt, unit_price, periodo, series,
       min(number), max(number), count(*)
from (select t.*,
             row_number() over
                 (partition by parent_id, transaccion_code, way_to_pay, type_of_receipt, unit_price, periodo, series
                  order by number
                 ) as seqnum
      from t
     ) t
group by parent_id, transaccion_code, way_to_pay, type_of_receipt, unit_price, periodo, series,
         (number - seqnum);
相关问题