sql - Duplicate rows using left join -
suppose have table this:
+----+--------+-------------+----------------+--------+ | id | parent | description | numberofthings | number | +----+--------+-------------+----------------+--------+ | | null | | 1 | null | | b | null | b | 3 | null | | c | null | c | 2 | null | +----+--------+-------------+----------------+--------+
and want use numberofthings
x create children number of things:
+-----+--------+-------------+----------------+--------+ | id | parent | description | numberofthings | number | +-----+--------+-------------+----------------+--------+ | | null | | 1 | null | | b | null | b | 3 | null | | c | null | c | 2 | null | | a-1 | | | 1 | 1 | | b-1 | b | b | 1 | 1 | | c-1 | c | c | 1 | 1 | | b-2 | b | b | 1 | 2 | | c-2 | c | c | 1 | 2 | | b-3 | b | b | 1 | 3 | +-----+--------+-------------+----------------+--------+
how go doing this? have idea use left join , perhaps kind of wildcard on clause not sure begin this.
this using sql server 2012, believe there can solution isnt specific db engine.
sql fiddle first attempt: http://sqlfiddle.com/#!6/dcafc/2
it's bit messy, recursive cte can this:
with cte ( select id baseid, cast(id varchar(10)) id, cast(null varchar(1)) parent, description, numberofthings, numberofthings totalcount, 1 currentcount, null number numthings union select c.baseid, cast(c.baseid + '-' + cast(c.currentcount varchar(8)) varchar(10)) id, c.baseid parent, c.description, 1 numberofthings, c.totalcount, c.currentcount + 1 currentcount, c.currentcount number cte c c.currentcount <= c.totalcount ) select id, parent, description, numberofthings, number cte order case when parent null 0 else 1 end, number, id;
demo.
Comments
Post a Comment