3

when I execute following query.

select 30,60,90,120,150,180 from table

I get output given below enter image description here

But my desire output like, Want out in only one column.

 sequence 
   30
   60
   90
   120
   150
   180

Is this possible?

4

4 回答 4

6

UNION ALL可以在所有主要的 RDBMS 中使用

SELECT 30 "sequence" UNION ALL
SELECT 60 UNION ALL
SELECT 90 UNION ALL
SELECT 120 UNION ALL
SELECT 150 UNION ALL
SELECT 180

或使用 postgres 的generate_series()功能

SELECT * 
  FROM generate_series(30, 180, 30) "sequence";

输出:

| 序列 |
|-----------|
| 30 |
| 60 |
| 90 |
| 120 |
| 150 |
| 180 |

这是两个查询的SQLFIddle演示

于 2013-11-08T07:39:57.943 回答
1

正如其他答案所提到的,当您要生成的数据是这样的均匀间隔系列时,generate_series 是要走的路。如果没有,我喜欢 a_horse_with_no_name 的版本。另一种方法是:

select unnest('{30,60,90,120,150,180}'::int[]) as numbers
于 2013-11-08T11:52:35.280 回答
1

比使用 UNION ALL 短一点:

select *
from ( values (30), (60), (90), (120), (150), (180) ) as numbers (seq_no);

或者:

with numbers (seq_num) as (
  values (30), (60), (90), (120), (150), (180)
)
select *
from numbers;
于 2013-11-08T07:48:50.160 回答
1

正如@peterm 所说,进入 PostgreSQL 的方法是使用generate_series()

在其他支持递归 cte 的 RDBMS 中,您可以像这样使用它:

with recursive cte(sequence) as (
    select 30
    union all
    select sequence + 30
    from cte
    where sequence < 180
)
select *
from cte

此外,如果您的 RDMBS 支持窗口函数,并且您有一些表,并且您知道该表中始终存在至少 6 行,您可以这样做:)

select
    row_number() over(order by id) * 30
from temp
limit 6

sql fiddle demo

于 2013-11-08T08:15:33.163 回答