SQL 查询按范围分组

SQL query grouping by range

您好,有一个 table A,其中包含以下数据:

+------+-------+----+--------+
| YEAR | MONTH | PA | AMOUNT |
+------+-------+----+--------+
| 2020 | 1     | N  | 100    |
+------+-------+----+--------+
| 2020 | 2     | N  | 100    |
+------+-------+----+--------+
| 2020 | 3     | O  | 100    |
+------+-------+----+--------+
| 2020 | 4     | N  | 100    |
+------+-------+----+--------+
| 2020 | 5     | N  | 100    |
+------+-------+----+--------+
| 2020 | 6     | O  | 100    |
+------+-------+----+--------+

我想要以下结果:

+---------+---------+--------+
| FROM    | TO      | AMOUNT |
+---------+---------+--------+
| 2020-01 | 2020-02 | 200    |
+---------+---------+--------+
| 2020-03 | 2020-03 | 100    |
+---------+---------+--------+
| 2020-04 | 2020-05 | 200    |
+---------+---------+--------+
| 2020-06 | 2020-06 | 100    |
+---------+---------+--------+

我的数据库是 DB2/400。 我试过 ROW_NUMBER 分区、子查询,但我不知道如何解决这个问题。

你可以试试下面的-

select min(year)||'-'||min(month) as from_date,max(year)||'-'||max(month) as to_date,sum(amount) as amount from
(
select *,row_number() over(order by month)-
row_number() over(partition by pa order by month) as grprn
from t1
)A group by grprn,pa order by grprn

这在 tsql 中有效,猜猜你可以将它应用于 db2-400?

SELECT MIN(Dte) [From]
     , MAX(Dte) [To]
       --   ,PA
     , SUM(Amount)
FROM (

    SELECT year * 100 + month Dte
         , Pa
         , Amount
         , ROW_NUMBER() OVER (PARTITION BY pa ORDER BY year * 100 + month) +
             10000- (YEar*100+Month) rn

    FROM tabA a
) b
GROUP BY Pa
       , rn
ORDER BY [From]
       , [To]

诀窍是按 PA 分区并按日期排序的行号函数,这将为每个月增加一个,当添加到月份和月份的降序计数时,您将获得相同的数字连续几个月使用相同的 PA。你按 PA 分组,你做的分组,rn,得到组,然后 Bob 是你的叔叔。

我理解这是一个 gaps-and-island 问题,您希望将具有相同 PA.

的相邻行组合在一起

这是一种使用行号之间的差异来构建组的方法:

select min(year_month) year_month_start, max(year_month) year_month_end, sum(amount) amount
from (
    select a.*, year * 100 + month year_month
        row_number() over(order by year, month) rn1,
        row_number() over(partition by pa order by year, month) rn2
    from a
) a
group by rn1 - rn2
order by year_month_start