如何将SQL表拆分为一半并使用SQL Query将另一半行发送到新列?

Nay*_*_07 5 sql sql-server

Country    Percentage

India      12%
USA        20%
Australia  15%
Qatar      10%
Run Code Online (Sandbox Code Playgroud)

输出:

Country1    Percentage1     Country2     Percentage2
India       12%             Australia    15%
USA         20%             Qatar        10%
Run Code Online (Sandbox Code Playgroud)

例如,有一个表Country有百分比,我需要将表分成一半,并在新列中显示剩余的一半(即剩余的行).我还在文本中提供了表结构.

Gor*_*off 5

首先,这种类型的操作应该在应用层而不是在数据库中完成.也就是说,在数据库中查看如何执行此操作可能是一项有趣的练习.

我会使用条件聚合或pivot.请注意,SQL表本质上是无序的.您的基表没有明显的排序,因此值可以按任何顺序出现.

select max(case when seqnum % 2 = 0 then country end) as country_1,
       max(case when seqnum % 2 = 0 then percentage end) as percentage_1,
       max(case when seqnum % 2 = 1 then country end) as country_2,
       max(case when seqnum % 2 = 1 then percentage end) as percentage_2       
from (select c.*,
             (row_number() over (order by (select null)) - 1) as seqnum
      from country c
     ) c
group by seqnum / 2;
Run Code Online (Sandbox Code Playgroud)


Jay*_*esh 3

尝试这个

    declare @t table
(
Country VARCHAR(20),
percentage INT
)
declare @cnt int

INSERT INTO @T
VALUES('India',12),('USA',20),('Australia',15),('Quatar',12)

select @cnt = count(1)+1 from @t

;with cte
as
(
    select
    SeqNo = row_number() over(order by Country),
    Country,
    percentage
    from  @t
)
select 
*
from cte c1
left join cte c2
on c1.seqno = (c2.SeqNo-@cnt/2)
and c2.SeqNo >= (@cnt/2)
where c1.SeqNo <= (@cnt/2)
Run Code Online (Sandbox Code Playgroud)