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 2008 Forums
 Transact-SQL (2008)
 COUNT COLUMN VALUES

Author  Topic 

Kalaiselvan
Posting Yak Master

112 Posts

Posted - 2012-08-29 : 02:55:49
Hi,
I have a table with records following...

TABLEA:
[ID] [COL1] [COL2] [COL3] ... {COLn]
1 0 0 1 -1
2 1 1 1 0
3 -1 0 0 1

Need to find Number of -1,1 and 0 (Negative values, Positive values and zero values) for each rows. So i need the result set as

[ID] [NEG.COUNT] [POS.COUNT] [ZERO.COUNT]
1 1 1 2
2 0 3 1
3 1 1 2

Please help me to get the Query for this...

Regards,
Kalai

stepson
Aged Yak Warrior

545 Posts

Posted - 2012-08-29 : 03:31:21
Working with a limited nr of columns


with A
as
(
select 1 as id , 0 as col1, 0 as col2,1 as Col3, -1 as colN
union all
select 2 ,1,1,1,0
union all
select 3,-1,0,0,1 )


select id,
case when col1=-1 then 1 else 0 end + case when col2=-1 then 1 else 0 end + case when col3=-1 then 1 else 0 end + case when colN=-1 then 1 else 0 end as [Neg.Count],
case when col1=1 then 1 else 0 end + case when col2=1 then 1 else 0 end + case when col3=1 then 1 else 0 end + case when colN=1 then 1 else 0 end as [Pos.Count],
case when col1=0 then 1 else 0 end + case when col2=0 then 1 else 0 end + case when col3=0 then 1 else 0 end + case when colN=0 then 1 else 0 end as [Zero.Count]
from A
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2012-08-29 : 04:00:46
Or perhaps make it simpler?
DECLARE	@Sample TABLe
(
ID INT,
Col1 INT,
Col2 INT,
Col3 INT,
Col4 INT
);

INSERT @Sample
VALUES (1, 0, 0, 1, -1),
(2, 1, 1, 1, 0),
(3, -1, 0, 0, 1);

-- Solution by SwePeso
WITH cteSource(ID, theValue)
AS (
SELECT u.ID,
u.theValue
FROM @Sample AS s
UNPIVOT (
theValue
FOR theColumn IN (s.Col1, s.Col2, s.Col3, s.Col4) -- This list should hold all columns involved in the calculation. Only one change in one place!
) AS u
)
SELECT ID,
SUM(CASE WHEN theValue < 0 THEN 1 ELSE 0 END) AS [Neg Count],
SUM(CASE WHEN theValue > 0 THEN 1 ELSE 0 END) AS [Pos Count],
SUM(CASE WHEN theValue = 0 THEN 1 ELSE 0 END) AS [Zero Count]
FROM cteSource
GROUP BY ID
ORDER BY ID;



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page

Kalaiselvan
Posting Yak Master

112 Posts

Posted - 2012-08-31 : 08:01:10
I got this already with fixed columns. But my query need for n number of columns.
Columns count may varied, For those columns need to find the results.

Regards,
Kalai
Go to Top of Page
   

- Advertisement -