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.

8
  • what is NA? Is that null? Commented Apr 7, 2016 at 10:38
  • if you used 1/0 instead of P / NA, you could then use sum() with group by, which would give you the result you want. Commented Apr 7, 2016 at 10:43
  • what are the values contain in the fields?? Int or string??? Commented Apr 7, 2016 at 10:44
  • 1
    Group by clause is giving only first row data What aggregation function did you use with GROUP BY? Commented Apr 7, 2016 at 10:47
  • 1
    Is there a difference between this question and your last question? Commented Apr 7, 2016 at 10:56

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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;

6 Comments

missing GROUP BY
Nope, the GROUP BY clause serves no purpose here.
If you don't use GROUP BY, you'll combine all the rows for all the different users.
Then use where name = Anand
Why do you think he only wants the result for one user, not to do it for all the users?
|

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.