PHP ZCE mock test, interview preparation, daily lessons under chalk talk

Tuesday, June 7, 2016

MySQL - For each Row Print Columns/Flags with value equal to 1


One of my colleague came to me with this problem. It enjoyed solving it. Here, it is for you. Say, you are given a table like this with a given number of columns.

   id  Flag_1  Flag_2  Flag_3  Flag_4  Flag_5
------  --------  -------  --------  --------  -------
    1       1       1       1       1         1
    2       0       0       0       0         0
    3       1       1       0       1         0
    4       0       1       0       0         1
    5       1       0       1       0         1

Desired output is to have a comma separated list of "Flag Names" that are ON for each row. i.e.

   id  onFlags                             
------  ------------------------------------
    1  Flag_1,Flag_2,Flag_3,Flag_4,Flag_5  
    2                                      
    3  Flag_1,Flag_2,Flag_4,               
    4  Flag_2,Flag_5                       
    5  Flag_1,Flag_3,Flag_5   

It's not a generally required to print column names as a result of query. One easy solution is to fetch data in sql and then use some programming language to manipulate it. However, try running sql only to fetch it. I recommend to minimize the browser and try it on your own.

=============================================

SELECT
 id, CONCAT(flag1, flag2, flag3, flag4,flag5) AS onFlags
FROM
 (SELECT
   IF(Flag_1 = '1', 'Flag_1,', '') AS flag1,
   IF(Flag_2 = '1', 'Flag_2,', '') AS flag2,
   IF(Flag_3 = '1', 'Flag_3,', '') AS flag3,
   IF(Flag_4 = '1', 'Flag_4,', '') AS flag4,
   IF(Flag_5 = '1', 'Flag_5', '') AS flag5,
   id
 FROM
   Flags) AS a ;

1 comment:

  1. hey guys,useful study material for free
    http://www.kidsfront.com/govt-jobs-exams.html

    ReplyDelete