我不想连接任何东西。相反,如果一个表有多列,我想要一个SELECT
语句,然后返回每个列,就好像它们存在于不同的行中一样( ONE COLUMN )。实施例...
TABLE +--------+---------+---------+ +--------+ |Person1 | Person2 | Person3 | |Person | +========+=========+=========+ SELECT *ANSWER HERE* +========+ |Alex | Ben | Charlie | FROM PEOPLE |Alex | +--------+---------+---------+ ORDER BY *person*? +--------+ |Dale | Eric | Gary | |Ben | +--------+---------+---------+ RETURNS ------------> +--------+ |Charlie | ^^^ NOTE ABOVE HOW WE ^^^ +--------+ HAVE THREE COLUMNS |Dale | +--------+ |Eric | NOTE HOW WE ONLY +--------+ RETURN ONE COLUMN --------------> |Gary | +--------+
注意:我们从一个包含三列的表开始,现在返回一个结果,好像每一行都是独立的。
答案 0 :(得分:5)
您可以使用UNPIVOT,但UNION也可以使用..更改为UNION ALL以包含重复项..
SELECT Person1 [Person]
FROM People
UNION
SELECT Person2
FROM People
UNION
SELECT Person3
FROM People
如果您想尝试使用UNPIVOT来比较性能,它会是这样的。
SELECT DISTINCT
Person
FROM People
UNPIVOT (
Person
FOR Persons IN ([Person1],[Person2],[Person3])
) up
使用表值构造函数
SELECT DISTINCT
Person
FROM People
CROSS APPLY (VALUES(Person1),(Person2),(Person3)) t(Person)