簡體   English   中英

按固定記錄數分區

[英]Partition by fixed number of records

我想知道如何按固定數量的記錄對窗口進行分區。

示例( http://sqlfiddle.com/#!1/7df86 )。

CREATE TABLE Games 
(
 id serial primary key, 
 game_no integer not null, 
 points integer,
  constraint game_no unique (game_no)
);

INSERT INTO Games (game_no, points)
VALUES (3123, 5), (3126, 5), (3135, 8), (3128, null), (3130, 1), (3121, 11), 
(3132, 0), (3133, 4), (3110, 7), (3112, null), (3113, 12), (3125, 3),(3134, 8);

我希望將三個游戲的總點數相加,從最高的游戲編號開始,然后按游戲編號排序。 像這樣。

| GAME_NO | POINTS | SUM_THREE |
|---------|--------|-----------|
|    3135 |      8 |        20 |
|    3134 |      8 |        20 |
|    3133 |      4 |        20 |
|    3132 |      0 |         1 |
|    3130 |      1 |         1 |
|    3128 | (null) |         1 |
|    3126 |      5 |        13 |
|    3125 |      3 |        13 |
|    3123 |      5 |        13 |
|    3121 |     11 |        23 |
|    3113 |     12 |        23 |
|    3112 | (null) |        23 |
|    3110 |      7 |         7 |

如何在不使用子查詢的情況下使用窗口函數完成此操作? 我也不能使用例如with語句。 由於必須執行外部解析器,因此它只能是一個查詢(我無法控制)。 似乎很簡單,最近兩天我都在掙扎:)

您可以使用row_number函數除以3來為每組3個連續行分配唯一編號。 然后將sum作為每個組的分析函數。

SQL小提琴

with x(game_no, points, grp) as (
  select game_no, points,
         ceil(cast(row_number() over (order by game_no desc) as decimal)/ 3)
  from games
  )
select game_no, points,
       sum(points) over (partition by grp)
from x
order by game_no desc;

您可以使用內聯視圖而不是使用construct。

select game_no, points,
       sum(points) over (partition by grp)
from (
      select game_no, points,
             ceil(cast(row_number() over
                   (order by game_no desc) as decimal)/ 3) as grp
      from games
    ) as x
order by game_no desc;

結果

| GAME_NO | POINTS | SUM |
|---------|--------|-----|
|    3135 |      8 |  20 |
|    3134 |      8 |  20 |
|    3133 |      4 |  20 |
|    3132 |      0 |   1 |
|    3130 |      1 |   1 |
|    3128 | (null) |   1 |
|    3126 |      5 |  13 |
|    3125 |      3 |  13 |
|    3123 |      5 |  13 |
|    3121 |     11 |  23 |
|    3113 |     12 |  23 |
|    3112 | (null) |  23 |
|    3110 |      7 |   7 |

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM