Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Count Question

Author  Topic 

BigRetina
Posting Yak Master

144 Posts

Posted - 2006-02-07 : 09:13:51
Hello,

I have the following table (first four columns). I need to produce the last two columns...

Ch1 Ch2 Ch3 Ch4 NoOf3s NoOf7s
--- --- --- --- ------ ------
1 3 4 3 2 0
7 7 7 3 1 3
7 8 9 0 0 1

Columns NoOf3s and NoOf7s are calculated columns and they do not exist in the table. How can produce this resultset in one SQL statement?

thanks in advance

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2006-02-07 : 09:23:15
Create a UDF to do your counting.
See code below.
create table #ch
(
ch1 int,
ch2 int,
ch3 int,
ch4 int
)

insert into #ch
select 1, 3, 4, 3 union all
select 7, 7, 7, 3 union all
select 7, 8, 9, 0

create function dbo.count_no
(
@ch1 int,
@ch2 int,
@ch3 int,
@ch4 int,
@cnt_no int
)
returns int
as
begin
declare @count int

select @count = count(*)
from
(
select @ch1 as ch union all
select @ch2 union all
select @ch3 union all
select @ch4
) as c
where ch = @cnt_no
return @count
end


select ch1, ch2, ch3, ch4,
dbo.count_no(ch1, ch2, ch3, ch4, 3) as NoOf3s,
dbo.count_no(ch1, ch2, ch3, ch4, 7) as NoOf7s
from #ch



----------------------------------
'KH'


Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2006-02-07 : 14:55:56
This should do it:

select
ch1,
ch2,
ch3,
ch4,
NoOf3s =
case ch1 when 3 then 1 else 0 end +
case ch2 when 3 then 1 else 0 end +
case ch3 when 3 then 1 else 0 end +
case ch4 when 3 then 1 else 0 end,
NoOf7s =
case ch1 when 7 then 1 else 0 end +
case ch2 when 7 then 1 else 0 end +
case ch3 when 7 then 1 else 0 end +
case ch4 when 7 then 1 else 0 end
from
MyTable




CODO ERGO SUM
Go to Top of Page
   

- Advertisement -