how to remove duplicate data using mysql query

时间:2016-04-07 10:36:32

标签: mysql

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.

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;