Sql Server

1 down vote favorite

in Sql server 
name | [1 AUG]| [2AUG]| [3AUG]
prad | Present| Present| Lop
vas  | Present| Present| Lop

I want to count the number of 'Present' each person's Present Dates in a Month as I mention Above .please help How can I count row wise?

more ▼

asked Sep 01 '12 at 01:33 PM in Default

Parthasarathy gravatar image

60 3 6 8

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

(Off the top of my head...)

You could do something like:

SELECT CASE WHEN [1 aug] = 'Present' THEN 1 ELSE 0 END +
       CASE WHEN [2 aug] = 'Present' THEN 1 ELSE 0 END +
       CASE WHEN [31 aug] = 'Present' THEN 1 ELSE 0 END AS DaysPresentInAugust

An alternative would be to use the UNPIVOT statement

SELECT Name, DayOfAugust, PresentOrNot
FROM (SELECT Name, [1 Aug], [2 Aug], ..., [31 Aug] FROM <your table>) p
     (PresentOrNot FOR DayOfAugust IN ([1 Aug], [2 Aug], ..., [31 Aug])) AS unp

Something like that.

Note: all code untested. Suggestions only. I'm not on a machine with SQL Server to test this stuff...

more ▼

answered Sep 01 '12 at 02:16 PM

ThomasRushton gravatar image

ThomasRushton ♦
33.4k 14 20 44

(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.



asked: Sep 01 '12 at 01:33 PM

Seen: 374 times

Last Updated: Sep 01 '12 at 02:17 PM