代码之家  ›  专栏  ›  技术社区  ›  user2896120

用一行得到两种不同类型的和

  •  0
  • user2896120  · 技术社区  · 4 年前

    我有一张这样的桌子:

    id  code  total
    1   2     30
    1   4     60
    1   2     31
    2   2     10
    2   4     11
    

    我想做的是,基本上每个id有一行代码2的记录和该id所有代码的记录之和

    id  code2_total  overall
    1   61           121
    2   10           21
    

    我试过以下方法:

    select id
        , abs(sum(total) over (partition by id)) as overall
        , (select sum(total) from table where code = '2' group by id) as code2_total
       from table limit 1
    

    但是我在子查询错误中得到了多个项。我怎样才能实现这样的目标?

    1 回复  |  直到 4 年前
        1
  •  4
  •   Dale K    4 年前

    使用 group by 和一个常客 sum 有条件的 总和 (即使用 case 表达)。

    declare @MyTable table (id int, code int, total int);
    
    insert into @MyTable (id, code, total)
        values
        (1, 2, 30),
        (1, 4, 60),
        (1, 2, 31),
        (2, 2, 10),
        (2, 4, 11);
    
    select id
        , sum(case when code = 2 then total else 0 end) code2_total
        , sum(total) overall
    from @MyTable
    group by id
    order by id;
    

    退换商品

    身份证件 代码2_总计 全面的
    1. 61 121
    2. 10 21

    笔记 limit 1 MySQL不是SQL Server,在这里也帮不了你。

    还要注意,如我在这里所示,提供DDL+DML可以让人们更容易地提供帮助。