我有一个像这样的SQL select语句:
select FirstName, LastName, Age from People
这会给我一个像桌子的东西:
Peter Smith 34
John Walker 46
Pat Benetar 57
我想要的是将列标题插入第一行,如:
First Name Last Name Age
=========== ========== ====
Peter Smith 34
John Walker 46
Pat Benetar 57
有人可以建议如何实现这一目标吗?
您是否可以使用标题创建一个临时表并将数据附加到此处?
答案 0 :(得分:7)
上述任何一个答案都不会起作用,除非您的所有名字都按照排序顺序排在“第一”之后。
Select FirstName, LastName
from (
select Sorter = 1, FirstName, LastName from People
union all
select 0, 'FirstName', 'LastName') X
order by Sorter, FirstName -- or whatever ordering you need
如果你想对所有非varchar列执行此操作,则CONS(至少):
实现这一目标的SQL, not-recommended ,
Select FirstName, LastName, Age, DOB
from (
select Sorter = 1,
Convert(Varchar(max), FirstName) as FirstName,
Convert(Varchar(max), LastName) as LastName,
Convert(Varchar(max), Age) as Age,
Convert(Varchar(max), DOB, 126) as DOB
from People
union all
select 0, 'FirstName', 'LastName', 'Age', 'DOB') X
order by Sorter, FirstName -- or whatever ordering you need
答案 1 :(得分:1)
最轻的方法是做一个UNION:
SELECT 'FirstName' AS FirstName, 'LastName' AS LastName
UNION ALL
SELECT FirstName, LastName
FROM People
无需创建临时表。
答案 2 :(得分:0)
UNION All
是解决方案,但应指出:
示例:
Select Convert(varchar(25), b.integerfiled) AS [Converted Field]...
... Order by [Converted Field]