如何使用sql

时间:2019-10-15 06:55:49

标签: sql sqlite

我有四个桌子,

  1. 客户
  2. 订单
  3. 订单项
  4. 销售

“订单”表包含订单“已完成”或“正在处理”的状态。一旦订单完成,我会将销售信息存储在销售表中,将订单标记为已完成,还存储销售总额和余额表。 现在,我想从订单表中获取到期金额的客户名称,并从销售表中获取每个客户的余额。 我已使用此查询,但无法获得所需的结果。

输出为:

current output

所需的输出是:

desired output

Select c.Name As CustomerName, c.ContactNumber AS CustomerContactNumber, c.Location AS CustomerAddress, Sum(oi.Amount) As Amount 
from OrderItems oi 
  inner join Orders o on oi.OrderId=o.Id 
  inner join Customers c on o.CustomerId=c.Id 
Where o.Status=='Processing' Group By o.CustomerId

UNION

Select c.Name As CustomerName, c.ContactNumber AS CustomerContactNumber, c.Location AS CustomerAddress,SUM(s.Balance) As Balance 
from Sales s 
  inner join Customers c on s.CustomerId=c.Id 
Group By s.CustomerId

1 个答案:

答案 0 :(得分:0)

您不需要union,可以使用left joinsum(sales)与客户orders表连接起来。

Select c.Name As CustomerName
    , c.ContactNumber AS CustomerContactNumber
    , c.Location AS CustomerAddress
    , Sum(oi.Amount) As Amount
    , Sum(t2.Balance) As Balance    
from OrderItems oi 
inner join Orders o on oi.OrderId=o.Id 
inner join Customers c on o.CustomerId=c.Id 
left join
    (Select s.CustomerId
        , SUM(s.Balance) As Balance 
        from Sales s 
        inner join Customers c on s.CustomerId=c.Id 
        Group By s.CustomerId) t2 on t2.CustomerId = c.CustomerId
where o.Status=='Processing' 
Group By c.CustomerId, c.ContactNumber, c.Location