假设我有一个这样的表:
+------------+-----------+--+--+--+
| 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 | | | | |
+---------+--+--+--+--+
答案 0 :(得分: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
答案 1 :(得分: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