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.
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) .
To set a variable value in SQL server based on true / false result, CASE statements can be used.
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.
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.
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With