Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Case Statement To Increment Value

Trying to create a calculated column that would have a value based on the values in four other columns. Column 1, Coulmn 2, Column 3, Column 4 could be either Yes or No The end result in the calculated column, let's say called Progress, should be something along this line:

Progress = CASE
WHEN [Column1] = 'Yes' THEN Value+1
WHEN [Column2] = 'Yes' THEN Value+1
WHEN [Column3] = 'Yes' THEN Value+1
WHEN [Column4] = 'Yes' THEN Value+1
ELSE 0 END

Hope this makes sense as obviously the syntax for the above is not correct.

like image 605
user1886816 Avatar asked Apr 22 '13 19:04

user1886816


People also ask

How do you increment a value in SQL?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

Can we assign value in CASE statement in SQL?

To set a variable value in SQL server based on true / false result, CASE statements can be used.

Can CASE statement be used in update SQL?

Using CASE in an UPDATE StatementYou can also use CASE in an UPDATE statement. The SQL UPDATE statement is used to change values in an existing table.

Can you do a sum in a CASE statement SQL?

Let's get serious now! A CASE WHEN expression is often used with a SUM() function in more complex reports, which can be quite challenging for beginners. Even though you're probably used to using the SUM() function for summing values, it can also be used for counting.


2 Answers

Sounds like this is what you're going for.

Progress = 
CASE WHEN [Column1] = 'Yes' THEN 1 ELSE 0 END +
CASE WHEN [Column2] = 'Yes' THEN 1 ELSE 0 END +
CASE WHEN [Column3] = 'Yes' THEN 1 ELSE 0 END + 
CASE WHEN [Column4] = 'Yes' THEN 1 ELSE 0 END 

This will return 0 + 1 for each "Yes".

like image 97
Nick Vaccaro Avatar answered Sep 20 '22 01:09

Nick Vaccaro


In SQL Server:

SELECT  *
FROM    mytable
CROSS APPLY
        (
        SELECT  COALESCE(SUM(CASE val WHEN 'yes' THEN 1 END), 0)
        FROM    (VALUES (NULL)) q(v)
        UNPIVOT
                (
                val FOR col IN
                (column1, column2, column3, column4)
                ) c
        ) q (progress)

See SQLFiddle.

like image 42
Quassnoi Avatar answered Sep 22 '22 01:09

Quassnoi