SQL将列中的数据转换为一行

时间:2015-11-03 10:57:25

标签: sql rows

我在SQL中有一张表格如下:

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

我需要将其转换为:

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

我如何执行此操作SQL

3 个答案:

答案 0 :(得分:0)

尝试

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

答案 1 :(得分:0)

您应该按名称分组并获取每个值的最小值/最大值

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

答案 2 :(得分:0)

使用DISTINCT&子查询中的NOT NULL,因为值是文本而不是数字(因此SUM无效)。

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

输出

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。另外请考虑您的命名惯例,无论是否为复数(苹果和猕猴桃/香蕉)。