gpt4 book ai didi

sql - PostgreSQL 特定值的当前计数

转载 作者:行者123 更新时间:2023-11-29 13:14:06 26 4
gpt4 key购买 nike

我需要实现如下 View :

+------------+----------+--------------+----------------+------------------+
| Parent id | Expected | Parent Value | Distinct Value | Distinct Value 2 |
+------------+----------+--------------+----------------+------------------+
| 1 | 001.001 | 3 | 6/1/2017 | 5,000.00 |
| 1 | 001.002 | 3 | 9/1/2018 | 3,500.00 |
| 1 | 001.003 | 3 | 1/7/2018 | 9,000.00 |
| 2 | 002.001 | 7 | 9/1/2017 | 2,500.00 |
| 3 | 003.001 | 5 | 3/6/2017 | 1,200.00 |
| 3 | 003.002 | 5 | 16/8/2017 | 8,700.00 |
+------------+----------+--------------+----------------+------------------+

我在其中获得具有相同父项的不同子对象,但我无法使“预期”列起作用。那些零并不重要,我只需要让像“1.1”、“1.2”这样的子索引工作。我尝试了 rank() 函数,但它似乎并没有真正帮助。

感谢任何帮助,提前致谢。

我最初的尝试是这样的:

SELECT DISTINCT
parent.parent_id,
rank() OVER ( order by parent_id ) as expected,
parent.parent_value,
ct.distinct_value,
ct.distinct_value_2
FROM parent
LEFT JOIN (crosstab (...) )
AS ct( ... )
ON ...

最佳答案

在窗口函数中使用partition by parent_idorder by another_col 来定义按parent_id分组的顺序。

with parent(parent_id, another_col) as (
values (1, 30), (1, 20), (1, 10), (2, 40), (3, 60), (3, 50)
)

select
parent_id,
another_col,
format('%s.%s', parent_id, row_number() over w) as expected
from parent
window w as (partition by parent_id order by another_col);

parent_id | another_col | expected
-----------+-------------+----------
1 | 10 | 1.1
1 | 20 | 1.2
1 | 30 | 1.3
2 | 40 | 2.1
3 | 50 | 3.1
3 | 60 | 3.2
(6 rows)

关于sql - PostgreSQL 特定值的当前计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51310771/

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