0

I have a table, which shows information regarding trades. d_diff column shows the difference between endtime and begtime, measured in a number of days.

I want those rows, where d_diff > 1, to make duplicated (d_diff shows the number of duplicated rows.

enter image description here

The final dataset should look like in a table below. As you can see, in this table the difference between endtime and begtime is 1 (the table is more granular).

enter image description here

How can it be done? I tried to do kind of this

select * from main a
full outer join 
main b
on a.begtime <= b.endtime
0

2 Answers 2

1

You can use a recursive CTE to generate series of repeatable rows like this

WITH cte(begtime, endtime, d_diff, trade, tradedate, price, region, d_diff_decr) AS (
    SELECT 
        *, 
        d_diff AS d_diff_decr 
    FROM t
    UNION ALL
    SELECT 
        begtime, 
        endtime, 
        d_diff, 
        trade, 
        tradedate, 
        price, 
        region, 
        d_diff_decr - 1 AS d_diff_decr 
    FROM cte 
    WHERE d_diff_decr > 1
)
SELECT 
    begtime, 
    endtime, 
    d_diff, 
    trade, 
    tradedate, 
    price, 
    region 
FROM cte
ORDER BY trade
Sign up to request clarification or add additional context in comments.

Comments

1

You can inner join with a tally table / numbers list.

Example:

with tally as (
  select v from (values(1),(2),(3))v(v)
)
select m.* 
from main m
join tally t on t.v <= m.d_diff;

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.