2016-03-14 65 views
0

假設我有一個這樣的表:如何字段轉換到排在SQL

+------------+-----------+--+--+--+ 
| First name | Last name | | | | 
+------------+-----------+--+--+--+ 
| First 1 | Last 1 | | | | 
+------------+-----------+--+--+--+ 
| First 2 | Last 2 | | | | 
+------------+-----------+--+--+--+ 
| First 3 | Last 3 | | | | 
+------------+-----------+--+--+--+ 

我將如何創建一個顯示這樣

+---------+--+--+--+--+ 
| Name | | | | | 
+---------+--+--+--+--+ 
| First 1 | | | | | 
+---------+--+--+--+--+ 
| Last 1 | | | | | 
+---------+--+--+--+--+ 
| First 2 | | | | | 
+---------+--+--+--+--+ 
| Last 2 | | | | | 
+---------+--+--+--+--+ 
| First 3 | | | | | 
+---------+--+--+--+--+ 
| Last 3 | | | | | 
+---------+--+--+--+--+ 

回答

1
with fnames as 
(
select fname Name, ROW_NUMBER() over (order by fname,lname) rank from myTable 
), lnames as 
(
select lname Name, 0.5 + ROW_NUMBER() over (order by fname,lname) rank from myTable 
), 
merged as 
(
(select * from fnames) union (select * from lnames) 
) 
select Name from merged order by rank 
+0

兩種解決方案都可以工但是這個更容易消化。 – Luke101

1

數據假設每隔一列是查詢重複,並且沒有ID柱最初

WITH T (FirstName, LastName,Ranking) 
AS 
(
SELECT 
    FirstName, 
    LastName, 
    2* ROW_NUMBER() OVER(ORDER First Name, Last Name) AS Ranking --, other columns 
FROM TBL 
) 

SELECT Name --, other columns 
FROM 
(
SELECT FirstName AS Name, 
Ranking-1 as r--, other columns 
FROM T 

UNION 

SELECT LastName AS Name, 
Ranking as r--, other columns 
FROM T 
) Tbl ORDER BY r ASC