如何在SQL中以其值的频率将行转换为列

时间:2019-04-11 18:12:31

标签: mysql sql

如何在SQL中以其值的频率将行转换为列?

例如:我有如下所示的数据:

Input Data

预期输出为:

expected output

3 个答案:

答案 0 :(得分:3)

我将值放在列中:

select sum(apple) as num_apples,
       sum(banana) as num_bananas,
       sum(orange) as num_oranges,
       sum(strawberry) as num_strawberries
from t;

对于大多数目的来说,这似乎已经足够了。但是,如果要取消枢纽设置:

select f.fruit,
       (case fruit
            when 'apple' then sum(apple),
            when 'banana' then sum(banana)
            when 'orange' then sum(orange) 
            when 'strawberry' then sum(strawberry)
        end) as num
from t cross join
     (select 'apple' as fruit union all
      select 'banana' as fruit union all
      select 'orange' as fruit union all
      select 'strawberry' as fruit
     ) f
group by f.fruit

答案 1 :(得分:0)

按客户分组,然后使用SUM来计算每列的单位>

SELECT 
    customer,
    SUM(apple) AS Apple,
    SUM(banana) AS Banana,
    SUM(orange) AS Orange,
    SUM(strawberry) AS Strawberry
GROUP BY customer

答案 2 :(得分:0)

每个水果都带有UNION ALL:

select sum(apple) countofcustomer, 'Apple' Fruits from tablename
union all
select sum(banana), 'Banana' from tablename
union all
select sum(orange), 'Orange' from tablename
union all
select sum(strawberry), 'Strawberry' from tablename