简体   繁体   中英

how to get the count of columns with same value for each row in sql

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

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
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  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM