我有一个这样的SQL选择语句:
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
有人可以建议如何实现吗?
您能否用标题创建一个临时表并将数据附加到此表?
除非您的所有名字都按排序顺序在“ first”之后,否则上述两个答案都不会起作用。
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(但 不推荐 )是
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