在sql server
中,如果我有这样的表:
id | name
-------------
1 | x
2 | y
3 | z
我想创建一个存储过程以将结果返回到一行 像这样:
x | y | z
我的代码是:
alter PROCEDURE getSupervisorEvaluationPercentages
(
@FirstSupervisorNumber nvarchar(6),
@Year int
)
as
DECLARE @Count INT
DECLARE @OptionID INT
DECLARE @getOptionID CURSOR
declare @OptionCountTb table(c int)
SET @getOptionID = CURSOR FOR
SELECT Id FROM ObjectiveOption
OPEN @getOptionID
FETCH NEXT
FROM @getOptionID INTO @OptionID
WHILE @@FETCH_STATUS = 0
BEGIN
select @Count = (select COUNT(Id) from EvaluationProcess
where FirstSupervisorNumber = @FirstSupervisorNumber and Year = @Year and FirstSupervisorEvaluation = @OptionID)
insert into @OptionCountTb values(@Count)
FETCH NEXT
FROM @getOptionID INTO @OptionID
END
CLOSE @getOptionID
DEALLOCATE @getOptionID
我想将表@OptionCountTb
的值显示为单行
答案 0 :(得分:1)
PIVOT是其中一种方式 http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx
答案 1 :(得分:0)
select
name + ' '
from TableName
for xml path('')
答案 2 :(得分:0)
CREATE TABLE t1(id int,name varchar(10))
INSERT INTO t1
VALUES(1,'x'),
(2,'y'),
(3,'z')
SELECT STUFF((select '|'+name from t1 for XML path('')),1,1,'')
答案 3 :(得分:0)
试试这个解决方案:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + [name]
from t01
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + ' from
(
select [name]
from t01
) x
pivot
(
count([name])
for name in (' + @cols + ')
) p where 1=2 '
print(@query)
execute(@query)