1

I need to achieve a view such as:

+------------+----------+--------------+----------------+------------------+
|  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 |
+------------+----------+--------------+----------------+------------------+

where I get distinct child objects that have same parents, but I cannot make the "Expected" column work. Those zeros don't really matter, I just need to get subindex like "1.1", "1.2" to work. I tried rank() function but it seems it doesnt really help.

Any help appreciated, thanks in advance.

My initial try looks like this:

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 ...

1 Answer 1

1

Use partition by parent_id in the window function and order by another_col to define the order in groups by 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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.