我有一个检索两列的查询。
像这样:
select subscription_id, months from subscriptions;
现在,结果如下:
subscription_id months
1254 4
5896 1
8965 3
我想在查询结果中添加动态的右侧列,取决于检索的月数。如果一条记录的结果是4,我将在接下来的4列中为同一行添加值4,依此类推。
示例:
subscription_id months 0 1 2 3 4 5
1254 4 4 4 4 4 4
5896 1 1 1
8965 3 3 3 3 3 3
注意:我使用的是Oracle 10g,无法使用pivot。
答案 0 :(得分:1)
一种方法:
select
subscription_id,
months,
CASE WHEN MONTHS >= 0 THEN MONTHS END Month_0,
CASE WHEN MONTHS >= 1 THEN MONTHS END Month_1,
CASE WHEN MONTHS >= 2 THEN MONTHS END Month_2,
CASE WHEN MONTHS >= 3 THEN MONTHS END Month_3,
CASE WHEN MONTHS >= 4 THEN MONTHS END Month_4,
CASE WHEN MONTHS >= 5 THEN MONTHS END Month_5,
CASE WHEN MONTHS >= 6 THEN MONTHS END Month_6,
CASE WHEN MONTHS >= 7 THEN MONTHS END Month_7,
CASE WHEN MONTHS >= 8 THEN MONTHS END Month_8,
CASE WHEN MONTHS >= 9 THEN MONTHS END Month_9,
CASE WHEN MONTHS >= 10 THEN MONTHS END Month_10,
CASE WHEN MONTHS >= 11 THEN MONTHS END Month_11,
CASE WHEN MONTHS >= 12 THEN MONTHS END Month_12
from subscriptions;