2

I have my data is like this in table.

 name  day1  day2 day3 
 Anand  P     NA   NA 
 Anand  NA    P    NA 
 Anand  NA   NA  P 


I want result like this

name  day1 day2 day3
Anand P    P     P 

Group by clause is giving only first row data. Please suggest me mysql query. you can assume table name as att_table.

Anand jha
  • 31
  • 2

2 Answers2

4

You can use NULLIF to replace the NA value with NULL, and then use MAX() to get the non-null value within each group.

SELECT name, MAX(NULLIF(day1, 'NA')) AS day1, MAX(NULLIF(day2, 'NA')) AS day2, MAX(NULLIF(day3, 'NA')) AS day2
FROM att_table
GROUP BY name
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Try this:

SELECT
  name,
  GROUP_CONCAT(day1),
  GROUP_CONCAT(day2),
  GROUP_CONCAT(day3)
FROM att_table
GROUP BY name;

If 'NA' is a string and not SQL's NULL value, try this instead:

SELECT
  name,
  GROUP_CONCAT(IF(day1 = 'NA', NULL, day1)),
  GROUP_CONCAT(IF(day2 = 'NA', NULL, day2)),
  GROUP_CONCAT(IF(day3 = 'NA', NULL, day3))
FROM att_table
GROUP BY name;
Adrien Brunelat
  • 4,492
  • 4
  • 29
  • 42