gpt4 book ai didi

sql - 在 SQL 中使用窗口函数运行总计 "matches"

转载 作者:行者123 更新时间:2023-11-29 12:47:53 27 4
gpt4 key购买 nike

我想创建一个窗口函数来计算当前行中字段的值出现在当前行之前的有序分区部分的次数。为了使这个更具体,假设我们有一个这样的表:

| id| fruit  | date |
+---+--------+------+
| 1 | apple | 1 |
| 1 | cherry | 2 |
| 1 | apple | 3 |
| 1 | cherry | 4 |
| 2 | orange | 1 |
| 2 | grape | 2 |
| 2 | grape | 3 |

我们想创建一个这样的表(为清楚起见省略日期列):

| id| fruit  | prior |  
+---+--------+-------+
| 1 | apple | 0 |
| 1 | cherry | 0 |
| 1 | apple | 1 |
| 1 | cherry | 1 |
| 2 | orange | 0 |
| 2 | grape | 0 |
| 2 | grape | 1 |

请注意,对于 id = 1,沿着有序分区移动,第一个条目“apple”不匹配任何内容(因为隐含集为空),下一个水果“cherry”也不匹配。然后我们再次得到'apple',这是一场比赛等等。我想象 SQL 看起来像这样:

SELECT
id, fruit,
<some kind of INTERSECT?> OVER (PARTITION BY id ORDER by date) AS prior
FROM fruit_table;

但我找不到任何看起来合适的东西。 FWIW,我正在使用 PostgreSQL 8.4。

最佳答案

您可以在没有窗口函数的情况下通过self-left joincount() 优雅地解决这个问题:

SELECT t.id, t.fruit, t.day, count(t0.*) AS prior
FROM tbl t
LEFT JOIN tbl t0 ON (t0.id, t0.fruit) = (t.id, t.fruit) AND t0.day < t.day
GROUP BY t.id, t.day, t.fruit
ORDER BY t.id, t.day

如果您的目的是使用窗口函数,那么这个应该可行:

SELECT id, fruit, day
,count(*) OVER (PARTITION BY id, fruit ORDER BY day) - 1 AS prior
FROM tbl
ORDER BY id, day

If frame_end is omitted it defaults to CURRENT ROW.

  • 您有效地计算了前几天有多少行具有相同的 (id, fruit) - 包括当前行。这就是 - 1 的用途。

关于sql - 在 SQL 中使用窗口函数运行总计 "matches",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9368691/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com