两个不同表中的总和单独列

时间:2018-04-11 15:50:00

标签: sql sqlite

我有桌子

Allocations:
|allocationid|     item     |     job     |    amount   |
|1           |     item1    |     jobname |      50     |
|2           |     item1    |     jobname |      30     |
|3           |     item2    |     jobname |      20     |

和表格

InventoryAdjustLog:
|   logid    |      item    |     customer |   usage    |
|   1        |     item1    |     jobname  |    70      |
|   2        |     item1    |     jobname  |     5      |
|   3        |     item2    |     jobname  |     15     |

前表是对作业所需材料的估计,后一表是实际用途。

我想对此数据运行一个查询,该查询将返回Allocations表中所有类似项目的总和,以及在InventoryAdjustLog表中执行所有类似项目的另一个总和。

使用此数据返回的示例将是

 |   Item    |     Job       |     Allocated     |     Usage       |
 |   item1   |     jobname   |     80            |    75           |
 |   item2   |     jobname   |     20            |    15           |

我写了以下查询

Select Allocations.item as Item ,Allocations.job as Job 
,sum(Allocations.ammount)as  Allocated,
sum(InventoryAdjustLog.usage) as Usage
from Allocations 
inner join InventoryAdjustLog on Allocations.job = InventoryAdjustLog.customer  
where Allocations.job= 'jobname' group by Allocations.item;

仅部分起作用,除了它对已经求和的行的每个实例求和。如下所示。由于连接了两行,并且两者都包含总和值80,因此它将两行合计为一行。

 |   Item    |     Job       |     Allocated     |     Usage       |
 |   item1   |     jobname   |240 (Should be 80) |    etc...       |
 |   item2   |     jobname   | 60 (Should be 20) |    etc...          |

对我的查询方法进行哪些修改或更改会返回所需的结果,如上一个表中所示?

我绝不是sql的专家,因此非常感谢任何指导。

Here is a SqlFiddle example

2 个答案:

答案 0 :(得分:2)

您遇到问题,因为两个表都有重复项。一种解决方案是在进行聚合之前使用union all组合数据:

Select aia.item, aia.job,
       sum(aia.allocation)as  allocation,
       sum(aia.usage) as Usage 
from (select item, amount as allocation, 0 as usage, job
      from Allocations 
      union all
      select item, 0, usage, customer
      from InventoryAdjustLog 
     ) aia  
where aia.job = 'jobname'
group by aia.item, aia.job;

the slider documentation是一个SQL小提琴。

答案 1 :(得分:0)

SELECT
    item,
    job,
    SUM(amount) AS Allocated,
    SUM(usage) AS usage
FROM
    (
    SELECT
        item,
        job,
        amount,
        0 AS usage
    FROM 
        Allocations
    UNION ALL
    SELECT
        item,
        job,
        0 AS amount,
        usage
    FROM 
        InventoryAdjustLog  
    )
GROUP BY
    item,
    job
相关问题