这是一个面试问题。
如果我有这样的表:
ID FirstName LastName
-- --------- --------
1 Aaron Aames
2 Malcolm Middle
3 Zamon Zorr
如何获得看起来像这样的输出?
Aaron Aames
Aames Malcolm
Malcolm Middle
Middle Zamon
Zamon Zorr
注意:如果您需要特定的方言,请使用T-SQL。
答案 0 :(得分:2)
这是使用自联接的另一种方式。
CREATE TABLE temp (ID INT IDENTITY, FirstName VARCHAR(25), LastName VARCHAR(25));
INSERT INTO temp VALUES
(N'Aaron', N'Aames'),
(N'Malcolm', N'Middle'),
(N'Zamon', N'Zorr');
WITH names(ID, Name, ColNum) AS(
SELECT
ID, FirstName, 1
FROM temp
UNION ALL
SELECT
ID, LastName, 2
FROM temp
),
numbered AS(
SELECT
rn = ROW_NUMBER() OVER(ORDER BY ID, ColNum),
Name
FROM names
)
SELECT
n.Name AS Name1, n2.Name AS Name2
FROM numbered n
INNER JOIN numbered n2
ON n.rn = n2.rn - 1
DROP TABLE temp
答案 1 :(得分:1)
你的声誉很高,所以这不仅仅是“他们在采访中问我”这样的问题。
有几种方法。我想我要采取的是union all
。认识到每一行都来自表格。其余的是加入一行到下一行。所以,这表明:
select firstname, lastname
from likethis t
union all
select t.lastname, lead(t.firstname) over (order by id)
from likethis t
唉,这会给你六行而不是五行,所以需要过滤掉最后一行:
select firstname, lastname
from (select firstname, lastname
from likethis t
union all
select t.lastname, lead(t.firstname) over (order by id)
from likethis t
) t
where lastname is not null
order by firstname;
注意:我无法确定排序条件是按字母顺序还是按字母顺序排列;这些解决方案假设它是按字母顺序排列的。
第二个注意:我猜这不是他们想到的解决方案。他们可能正在寻找自我加入。但是,当lead()
为你工作时,为什么还要烦恼呢。
答案 2 :(得分:0)
我认为可以通过这种方式解决:
SELECT
t.LastName AS FirstName, t2.FirstName AS LastName
FROM
t
INNER JOIN t as t2 ON t2.ID - 1 = t.ID
UNION
SELECT
t3.FirstName, t3.LastName
FROM t AS t3
如果我已正确检查,则应按以下方式提供最终结果集:
Aaron Aames <= originates from t3: where t3.ID = 1
Aames Malcolm <= originates from (t1, t2) Join: where t2.ID = 2 and t.ID = 1
Malcolm Middle <= originates from t3: where t3.ID = 2
Middle Zamon <= originates from (t1, t2) Join: where t2.ID = 3 and t.ID = 2
Zamon Zorr <= originates from t3: where t3.ID = 3