Click here to Skip to main content
15,921,660 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I have a table with some columns and values. I need the count of only occupied values excluding null values and empty field in one single query.Any help will be really appreciated .Thanks in advance.

What I have tried:

id     Name      mob            address      gender      Dob

1      Sara     9884436546       NULL          F         NULL
2      Math                      abc city      M         
3      Asyu      NULL                          NULL      1994-05-29

Here the o/p should be like this 
id 1 : Count =3
id 2:  count =3
id 3:  count =2
Posted
Updated 30-May-18 22:55pm

1 solution

Assuming that it is only this table you are interested in then this simple technique would work
SQL
;with x as 
(
	SELECT id, hasvalue = CASE WHEN ISNULL([Name],'') <> '' THEN 1 ELSE 0 END FROM #test
	UNION ALL
	SELECT id, hasvalue = CASE WHEN ISNULL(mob,'') <> '' THEN 1 ELSE 0 END FROM #test
	UNION ALL
	SELECT id, hasvalue = CASE WHEN ISNULL([address],'') <> '' THEN 1 ELSE 0 END FROM #test
	UNION ALL
	SELECT id, hasvalue = CASE WHEN ISNULL(gender,'') <> '' THEN 1 ELSE 0 END FROM #test
	UNION ALL
	SELECT id, hasvalue = CASE WHEN ISNULL(Dob,'') <> '' THEN 1 ELSE 0 END FROM #test
)
select id, SUM(hasvalue) from x group by id

Comments:
- I duplicated your table into #test, replace that with your table name
- You need to use UNION ALL - it won't work with just UNION (as duplicates will be removed)
- Your data had a blank (not NULL) date - I trust you have not stored that date in a varchar column!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900