我遇到了显示前六条记录的情况。 FirstCol
中的前3个记录和SecondCol
中的后3个记录。我的查询是这样的:
select top 6 [EmpName]
from [Emp ]
order by [Salary] Desc
结果:
[EmpName]
----------------------
Sam
Pam
Oliver
Jam
Kim
Nixon
但我希望结果看起来像这样:
FirstCol SecondCol
Sam Jam
Pam Kim
Oliver Nixon
答案 0 :(得分:2)
; WITH TOP_3 AS
(
select TOP 3 [EmpName]
,ROW_NUMBER() OVER (ORDER BY [Salary] Desc) rn
from [Emp ]
order by [Salary] Desc
),
Other3 AS
(
SELECT [EmpName]
,ROW_NUMBER() OVER (ORDER BY [Salary] Desc) rn
FROM Employees
ORDER BY [Salary] DESC OFFSET 3 ROWS FETCH NEXT 3 ROWS ONLY
)
SELECT T3.[EmpName] , O3.[EmpName]
FROM TOP_3 T3 INNER JOIN Other3 O3
ON T3.RN = O3.RN
ORDER BY T3.RN ASC
答案 1 :(得分:1)
你可以使用几个窗口函数来做到这一点,这有点难看,但它会得到你想要的结果:
;with data as
(
-- get your Top 6
select top 6 empname, salary
from emp
order by salary desc
),
buckets as
(
-- use NTILE to split the six rows into 2 buckets
select empname,
nt = ntile(2) over(order by salary desc),
salary
from data
)
select
FirstCol = max(case when nt = 1 then empname end),
SecondCol = max(case when nt = 2 then empname end)
from
(
-- create a row number for each item in the buckets to return multiple rows
select empname,
nt,
rn = row_number() over(partition by nt order by salary desc)
from buckets
) d
group by rn;
见SQL Fiddle with Demo。这使用函数NTILE
,这将获取六行的数据集并将其拆分为两个桶 - 桶1中的3行和桶2中的3行。(2)
内的NTILE
是用于确定桶的数量。
接下来,我使用row_number()
为每个存储桶中的每一行创建一个唯一值,这允许您为每列返回多行。