您可以使用多個窗口函數做到這一點,這是一種醜陋的,但它會得到你想要的結果:
;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行。NTILE
中的(2)
用於確定桶的數量。
接下來,我使用row_number()
爲每個存儲桶中的每行創建唯一值,這允許您爲每列返回多行。
爲什麼不只是在UI上格式化這樣的結果?爲什麼他們需要像這樣從數據庫中返回? – Kritner 2014-09-10 19:04:51
通過SQL Server以這種方式格式化它可能會使服務器工作速度變慢。正如@Kritner所說的那樣,通常情況下將它放到UI中,然後按照您想要的樣式進行格式化。更好,更快,更容易。 – Hoh 2014-09-10 19:06:44
嗨Kritner,這是我們的要求。謝謝 – user3583912 2014-09-10 19:18:22