Wednesday, March 7, 2012

Multiple column result from one table

Hi,
I have a table like this :

TimeIDApplicationLoginState
1App1login10
1App2login21
1App3login31
1App1login40
1App1login51
1App4login10
2App1login10
2App2login20
2App3login31
2App1login40
2App1login51
2App4login10
3App1login10
3App2login21
3App3login31
3App1login40
3App1login51
3App4login10

And I want a result like this
TimeID (state=0) (state=1)
1 3 3
2 4 2
3 3 3

I use this code :

set nocount on
declare @.timeid1 int
declare @.timeid2 int
declare @.timeid int
declare @.sessionstate int
declare @.count1 int
declare @.count2 int
declare @.count int
declare @.aux int

declare txt_cursor cursor for

select timeid, sessionstate , count(login) from metromaster
where sessionstate = 0
group by timeid, sessionstate
UNION
select timeid, sessionstate , count(login) from metromaster
where sessionstate = 1
group by timeid, sessionstate
order by timeid

open txt_cursor
select @.aux = 0
fetch next from txt_cursor into @.timeid, @.sessionstate, @.count
while (@.@.fetch_status = 0)
begin
if @.aux = 0
begin
select @.timeid1 = @.timeid
select @.count1 = @.count
select @.aux =1
end
else
begin
select @.timeid2 = @.timeid
select @.count2 = @.count
select @.aux = 2
end
if @.aux = 2
begin
--select @.timeid1, @.count1, @.sessionstate, @.count2, @.timeid2
select @.timeid1, @.count1, @.count2
select @.aux = 0
end
fetch next from txt_cursor into@.timeid, @.sessionstate, @.count

end
close txt_cursor
deallocate txt_cursor
set nocount off

But it create a lot of blank row and field header.
Does anyone know an other methode ??

Thanks.SELECT timeid,
COUNT(CASE state WHEN 0 THEN 1 END) AS state_0,
COUNT(CASE state WHEN 1 THEN 1 END) AS state_1
FROM metromaster
GROUP BY timeid

--
David Portas
----
Please reply only to the newsgroup
--

No comments:

Post a Comment