dp6319 2016-05-18 11:35
浏览 9
已采纳

mysql总数和多行的差异

I'm new to mysql. I'm trying to write a query to calculate the total and difference for multiple rows, and then put them in specific columns.

Eg. I want to sum all Entity'A' of Type'1' then subtract from the result, the sum of Entity'A' of type'0'. While simultaneously populating a table to show where this difference is positive or negative.

Sample table:

Entity Type   Value
A      1      200
B      1      500
C      0      350
B      0      150
C      1      100
A      1      50
A      1      350

Expected Output:

Entity    Diff-Positive    Diff-Negative
A         600
B         350
C                          250

Note that Entity'A' for example may not have an entry for Type'0'

  • 写回答

1条回答 默认 最新

  • dqbh8054 2016-05-18 11:39
    关注

    This is basically aggregation. You need a conditional to split the values into separate columns. One way uses greatest():

    select entity,
           greatest(sum(case when type = 1 then value else - value end), 0) as diff_positive,
           greatest(sum(case when type = 0 then value else - value end), 0) as diff_positive    
    from t
    group by entity;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算