中被賦予一個包含兩列(1-字符串類型,另一個 - 數字類型)的表。我需要一個查詢(使用命令:join和rownum),其中每行被授予第二列指定的次數。 例如:查詢中,每行在第二列(sql,oracle)
col1 col2
---- ----
apple 4
melon 1
banana 2
結果:
apple
apple
apple
apple
melon
banana
banana
中被賦予一個包含兩列(1-字符串類型,另一個 - 數字類型)的表。我需要一個查詢(使用命令:join和rownum),其中每行被授予第二列指定的次數。 例如:查詢中,每行在第二列(sql,oracle)
col1 col2
---- ----
apple 4
melon 1
banana 2
結果:
apple
apple
apple
apple
melon
banana
banana
假設SQL服務器,這是通過明智地使用了提示表的可能的(在這個例子中使用sys.all_columns
,其大小是對上限可以生成的行數)並計算索引號範圍的部分總和,如下所示:
;with Ranges as (
select
col1,
(select coalesce(sum(t2.col2), 0)+1
from MyTable t2 where t2.col1<t1.col1) as indexStart,
(select coalesce(sum(t2.col2), 0)
from MyTable t2 where t2.col1<=t1.col1) as indexEnd
from
MyTable t1
)
,TallyTable as (
select
row_number() over (order by c.object_id, c.column_id) as number
from
sys.all_columns c
)
select
r.col1
from
Ranges R, TallyTable T
where
T.number between r.indexStart and r.indexEnd
儘管如所示通過對OP的評論,這不被推薦,並且很可能有更好的解決方案來解決您的業務問題。
假設你正在使用SQL Server,使用遞歸CTE
會做這項工作很好
YourTable
選擇的每一行,添加計數器到結果集。在給定的列col2
SQL語句
;WITH q AS (
SELECT col1, cnt = 1
FROM YourTable
UNION ALL
SELECT q.col1, cnt + 1
FROM q
INNER JOIN YourTable yt ON yt.col1 = q.col1
WHERE cnt < yt.col2
)
SELECT col1
FROM q
OPTION (MAXRECURSION 0)
測試腳本
;WITH YourTable(col1, col2) AS (
SELECT 'apple', 4
UNION ALL SELECT 'melon', 1
UNION ALL SELECT 'banana', 2
)
, q AS (
SELECT col1, cnt = 1
FROM YourTable
UNION ALL
SELECT q.col1, cnt + 1
FROM q
INNER JOIN YourTable yt ON yt.col1 = q.col1
WHERE cnt < yt.col2
)
SELECT col1
FROM q
OPTION (MAXRECURSION 0)
我不習慣SQL Server需要語句前的語句終止字符的事實... – 2012-03-28 07:48:37
由於你沒有給一個DBMS值我假設PostgreSQL:
with test_data (col1, col2) as (
values ('apple', 4), ('melon', 1), ('banana', 2)
)
select col1
from (
select col1, generate_series(1, col2)
from test_data
) t
哦親愛的上帝。他們現在做了什麼 – bernie 2012-03-27 23:22:11
這是什麼SQL引擎? MySQL的? Sql Server?甲骨文? DB2? – mellamokb 2012-03-27 23:22:21
「取消組合」功能... – Glenn 2012-03-27 23:29:00