Skip to content
Advertisement

How to Count or Sum the String columns values

I have employees attendance table from date 1 to 31 with column names like 1, 2, 3, 4 5…..31 and datatype is nVarchar(5)

I am adding values in those columns (P, H, A) for example:

P = Present A = Absence H = Holiday

Now i want to calculate Total (P=Present) in last column that is [TotalPresnets] of Employee. How to calculate (Count) the string values.

Advertisement

Answer

Because you made 31 columns, every type of manipulation will involve fetching all 31 of those columns. This is one of a million reasons why this design is going to cause you a lot of pain. So, I have to say you need to consider changing this design!

If you must stick with this, you will end up with code something like this:

select
    EmployeeID,
    (
        case when Day0 = 'P' then 1 else 0 end
        + case when Day1 = 'P' then 1 else 0 end
        + case when Day2 = 'P' then 1 else 0 end
        ...
        + case when Day31 = 'P' then 1 else 0 end
    ) as TotalPresent
from
    Attendance

Another ugly solution would be to use dynamic SQL to generate the query above.

In general, when you are forced into such ugly solutions, it’s a good indication that you are approaching the problem wrong.

Note also that this is some 40 lines of code for a very basic operation on a single row. Carrying this technique into the rest of your application is going to cause far more headaches. Imagine if you had to change any logic in here; what should be one line is now 31.

A better design would yield more intuitive / maintainable / readable code:

select
    EmployeeID,
    count(*) TotalPresent
from
    EmployeeDailyAttendance eda
    inner join Days d on d.ID = eda.DayID
where
    eda.Code = 'p'
group by
    EmployeeID
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement