1

I have a table in SQL that looks like:

name  age apples banana kiwi
mary  5   R3.00  null   null
mary  5   null   null   r6.00
mary  5   null   r9.50  null
joane 8   null   r9.60  null
joane 8   r5.00  null   null

I need to convert it to:

name    age apples  banana  kiwi
joane   8   r5.00   r9.60   (null)
mary    5   R3.00   r9.50   r6.00

How do I do this is SQL?

Matt
  • 14,906
  • 27
  • 99
  • 149
Miss R
  • 23
  • 6

3 Answers3

0

Try

select sum(age), sum(apples), sum(banana), sum(kiwi) from table group by name

MusicLovingIndianGirl
  • 5,909
  • 9
  • 34
  • 65
Altynbek
  • 11
  • 7
0

You should just group by name and take min/max of each value

select 
    name, max(age) age, max(apples) apples, max(banana) banana, max(kiwi) kiwi
from table group by name
Ilia Maskov
  • 1,858
  • 16
  • 26
0

Use DISTINCT & NOT NULL in a sub query as the values are text not numbers (so SUM wont work).

SELECT DISTINCT yt.name, yt.age, 
(SELECT yta.apples FROM yourtable yta WHERE yta.name = yt.name AND yta.apples IS NOT NULL) AS apples, 
(SELECT ytb.banana FROM yourtable ytb WHERE ytb.name = yt.name AND ytb.banana IS NOT NULL) AS banana, 
(SELECT ytk.kiwi FROM yourtable ytk WHERE ytk.name = yt.name AND ytk.kiwi IS NOT NULL) AS kiwi
FROM yourtable yt

OUTPUT

name    age apples  banana  kiwi
joane   8   r5.00   r9.60   (null)
mary    5   R3.00   r9.50   r6.00

SQ FIDDLE: http://sqlfiddle.com/#!3/88bc53/11/0

N.B. Also please consider your naming convention, either all plural or not (apples & kiwi/banana).

Matt
  • 14,906
  • 27
  • 99
  • 149