在每行中插入空行

wr98u20j  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(243)

我有这样一个结果:

name
Sally
Dan
Andy
Jackson

我使用了以下查询:

SELECT name from NAMEINFO where nNameIndex<5

我想得到这样的结果:

name
Sally
(blank)
Dan
(blank)
Andy
(blank)
Jackson
(blank)

我试着这样问:

select name
from (
  select top 100 percent *
  from (
    SELECT nNameIndex, name
    FROM NAMEINFO 
    union all
    select nNameIndex, ''
    from NAMEINFO 
  ) as t
  order by 1
) as r

但结果是:

name
Sally
Dan
Andy
Jackson
(blank)
(blank)
(blank)
(blank)

我想在sql结果的每一行中插入空行。我应该在哪里更改代码以获得想要的结果?

slmsl1lt

slmsl1lt1#

select name, ROW_NUMBER() over (order by name) pos from NAMEINFO where nNameIndex < 5
union all
select '', ROW_NUMBER() over (order by name) from NAMEINFO where nNameIndex < 5
order by pos, name desc

但实际上,您不应该在数据库中这样做,而应该在消费应用程序中这样做。

aoyhnmkz

aoyhnmkz2#

在最初的查询中,您几乎可以得到:

select name
  from (
    SELECT nNameIndex, name
    FROM NAMEINFO 
    union all
    select nNameIndex, ''
    from NAMEINFO 
  ) as t
  order by nNameIndex
0x6upsns

0x6upsns3#

您可以尝试使用row_number()来获得结果。

DECLARE @table table(name varchar(50))

insert into @table
values 
('Sally')
,('Dan')
,('Andy')
,('Jackson');

SELECT name
from
(
select name, ROW_NUMBER() OVER (ORDER BY name) as rnk from @table
union all
SELECT '',ROW_NUMBER() OVER (ORDER BY (SELECT null)) as rnk  from @table
) as t
order by rnk,name desc
+---------+
|  name   |
+---------+
| Andy    |
|         |
| Dan     |
|         |
| Jackson |
|         |
| Sally   |
|         |
+---------+

相关问题