-2

I have a problem, and i want to convert row in table A as the data in table B, can anyone help me with this case in SQL?

convert row in table A as the data in table B

Amira Bedhiafi
  • 8,088
  • 6
  • 24
  • 60

2 Answers2

0

I would use a tally table.

-- create a tally table
select top 100 identity(int,1,1) as n
into  dbo.tally
from  master.sys.all_columns ac1
        cross join master.sys.all_columns ac2

alter table dbo.tally
  add constraint pk_tally_n
      primary key clustered (n) with fillfactor = 100

-- your table
create table A (id int, paid_at datetime, client_id int, price int, billing_cycle int)
insert into A values(234, '2019-01-01', 3543, 3600000,12)


-- the soution
select  a.id
      , dateadd(month, n - 1, paid_at) paid_at
      , a.client_id
      , price / a.billing_cycle price
      , 1 billing_cycle
from    A a
        join dbo.tally t on t.n <= a.billing_cycle
order by 1, 2
Steve
  • 710
  • 1
  • 6
  • 12
0

I think a recursive CTE is a simple method:

with recursive cte as (
      select id, paid_at, paid_at as paid_for, client_id, price / billing_cycle as price, billing_cycle, 1 as n
      from a
      union all
      select id, paid_at, paid_for + interval 1 month, price, billing_cycle, n + 1
      from cte
      where n < billing_cycle
     )
select id, paid_at, paid_for, client_id, price, 1 as billing_cycle
from cte;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • i also look from another problem like mine and also give the solution with recursive CTE, but i always get this error... So what must i do? " **Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'recursive cte as ( select id, paid_at, paid_at as paid_for, client_id, pri' at line 1** " – Faiz Agustira Feb 12 '21 at 06:26