如何将两个sql语句合并为一组行语句 [英] How to combine two sql statement as single set of row statement
本文介绍了如何将两个sql语句合并为一组行语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用两个sql语句.但是,当我合并两个查询时,我想得到一个单行结果.
但是,现在我得到两行.第二行,我想使用合并列在第一行中显示.
查看我的查询:
I am using two sql statement. But, i want to get one single row result when i combine both query.
But, now i am getting two rows. the second row, i want to display within the first row using combine columns.
see my query :
select
case
when monthid = 4 AND yearid = '2011' and typeid ='A'
then '2011'
when monthid = 3 AND yearid = '2012' and typeid ='A'
then '2012'
end as FinYear
* from Employee
Where
( monthid = 4 AND yearid = '2011' and typeid ='A'
) or
(monthid = 3 AND yearid = '2012' and typeid ='A'
)
What is the problem over here..?
推荐答案
在yu上面的查询中,获得2行,如:
2011
2012
您希望您的结果看起来像:
2011,2012
为此,您需要使用光标.光标将遍历您的结果并对它们执行操作:
Hi,
With the query above yu get 2 rows like:
2011
2012
You want your result to look like:
2011,2012
To do this you need to use a cursor. the cursor will loop through your results and perform an action on them:
declare @result varchar(max)
declare @rowdata varchar(4)
declare c1 cursor for select
case
when monthid = 4 AND yearid = '2011' and typeid ='A'
then '2011'
when monthid = 3 AND yearid = '2012' and typeid ='A'
then '2012'
end as FinYear
* from Employee
Where
( monthid = 4 AND yearid = '2011' and typeid ='A'
) or
(monthid = 3 AND yearid = '2012' and typeid ='A'
)
open c1
fetch c1 into @rowdata
while @@fetch_status=0
Begin
if @result is null
Select @Result=@rowdata
else
Select @Result=@Result + ','+@rowdata
fetch c1 into @rowdata
End
Close c1
deallocate c1
这将为您提供结果2011,2012
This will give you the result 2011,2012
这篇关于如何将两个sql语句合并为一组行语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文