特定值的PostgreSQL当前计数
我需要实现以下观点:特定值的PostgreSQL当前计数,sql,postgresql,Sql,Postgresql,我需要实现以下观点: +------------+----------+--------------+----------------+------------------+ | Parent id | Expected | Parent Value | Distinct Value | Distinct Value 2 | +------------+----------+--------------+----------------+------------------+ |
+------------+----------+--------------+----------------+------------------+
| 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 ...
在窗口函数中使用
partitionbyparent\u id
和orderbyanother\u col
来定义按parent\u 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)