1

eg: table

id a  b  c  d 
1  Y  Y  Y  N
2  N  Y  Y  N

what I need is

id a  b  c  d  e
1  Y  Y  Y  N  3
2  N  Y  Y  N  2
1
  • Tag your question with the database you are using. Commented Mar 16, 2020 at 11:17

2 Answers 2

2

SQL functions generally aggregate data across rows, not columns, so I don't think there's a generic way of doing this. You could, however, for this usecase, use a series of case expressions:

SELECT id, a, b, c, d,
       CASE a WHEN 'Y' THEN 1 ELSE 0 END + 
       CASE b WHEN 'Y' THEN 1 ELSE 0 END + 
       CASE c WHEN 'Y' THEN 1 ELSE 0 END + 
       CASE d WHEN 'Y' THEN 1 ELSE 0 END AS e
FROM   mytable
Sign up to request clarification or add additional context in comments.

4 Comments

if you value is only Y it is correct but if count N and Y this is not correct answer
@MBadrian According to the OP'd sample data, only Ys should be counted
hi Mureinik, thank you I got it but I want to insert the e column to existing table please help
Yes but i think about general solution for this problem
0
UPDATE  mytable SET e=
       CASE a WHEN 'Y' THEN 1 ELSE 0 END + 
       CASE b WHEN 'Y' THEN 1 ELSE 0 END + 
       CASE c WHEN 'Y' THEN 1 ELSE 0 END + 
       CASE d WHEN 'Y' THEN 1 ELSE 0 END 
FROM  

1 Comment

It may be a great answer, but without an explanation or where the error was, it would be hard for anyone to find it useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.