使用单行进行查询

时间:2018-06-04 15:09:13

标签: sql

enter image description here

请帮忙。问题出在图片中。

2 个答案:

答案 0 :(得分:1)

您可以执行条件聚合:

select id,
       sum(case when type = 'x' and location = 'L' then amount else 0 end) as sumofXandL,
       . . . 
from table t
group by id;

答案 1 :(得分:0)

您可以通过此查询轻松完成此操作

select
    test.id 
    , sum(test.XL_amount) as XL_amount
    , sum(test.XD_amount) as XD_amount
    , sum(test.Y_amount) as Y_amount
from(
    SELECT
    id
    ,case
      when type = 'X' and location = 'L' then amount
      else 0
    end as XL_amount
    ,case
      when type = 'X' and location = 'D' then amount
      else 0
    end as XD_amount
    ,case
      when type = 'Y'  then amount
      else 0
    end as Y_amount
    FROM test_table t
) test
group by test.id;
相关问题