我有一张这样的桌子:
id_begain | id_end | name | address | m_number
----------+--------+------+---------+-----------
1 | 5 | a | hyd | 099
7 | 9 | b | pne | 999
200 | 288 | c | bng | 1999
我需要这样的输出:
id name address m_number
----------------------------
1 a hyd 099
2 a hyd 099
3 a hyd 099
4 a hyd 099
5 a hyd 099
7 b pne 999
8 b pne 999
9 b pne 999
200 c bng 1999
201 c bng 1999
...
288 c bng 1999
答案 0 :(得分:1)
可以使用日历表方法轻松地解决此问题,其CTE包含可能出现在开始或结束列中的所有数字的顺序:
WITH numbers AS (
SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n AS id
FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n)
WHERE ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n BETWEEN 1 AND 10000
)
SELECT
t1.id,
t2.name,
t2.address,
t2.m_number
FROM numbers t1
INNER JOIN yourTable t2
ON t1.id BETWEEN t2.id_begain AND t2.id_end
ORDER BY
t1.id;
答案 1 :(得分:1)
您可以使用递归公用表表达式(tbl
是表):
with cte as (
select id_begin, id_end, name, address, m_number
from tbl
union all
select id_begin+1, id_end, name, address, m_number
from cte
where id_begin < id_end
)
select id_begin as id, name, address, m_number
from cte
order by 1;