1

I have a tableA

|Column1|Column2|Column3|
|NO     |NO     |YES    |
|YES    |YES    |NO     |
|NO     |NO     |NO     |

My requirement is to count the number of Yes or No per row and display the greatest (or equal to) of them. My sample output should be like:

|Column1|Column2|Column3|Answer
|NO     |NO     |YES    |No
|YES    |YES    |NO     |Yes
|NO     |NO     |NO     |No

I know i can use a where clause if my requirement was to count them column wise, but how do I get this to be done row wise?

2
  • have you try you? Commented Dec 6, 2017 at 8:56
  • If it is only a few columns, you can use a CASE WHEN clause Commented Dec 6, 2017 at 9:40

2 Answers 2

1

If there are only 3 fixed columns then you can get expected result set by using CASE statement

SELECT 
  *,
  CASE
    WHEN Column1 = Column2 
    THEN Column1 
    WHEN Column1 = Column3 
    THEN Column1 
    WHEN Column2 = Column3 
    THEN Column2 
    ELSE NULL 
  END answer 
FROM
  demo a 

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

Following query will work:

SELECT 
    c1,c2,c3,    
   (
     case when
       ROUND 
       (   
          (
            CHAR_LENGTH(concat_ws(" ",c1,c2,c3))
            - CHAR_LENGTH( REPLACE ( concat_ws(" ",c1,c2,c3), "NO", "") ) 
          ) / CHAR_LENGTH("NO")
       ) > ROUND 
       (   
          (
            CHAR_LENGTH(concat_ws(" ",c1,c2,c3))
            - CHAR_LENGTH( REPLACE ( concat_ws(" ",c1,c2,c3), "YES", "") ) 
          ) / CHAR_LENGTH("YES")
       )
        then 'NO'
        else 'YES'
        end
 )   
     AS Answer    
FROM t;

Comments

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.