SQL JOIN三个表来获取总值

时间:2016-09-17 08:17:44

标签: mysql group-by

adhocbills
- sequence
- invoice_number

adhocbills_lineitems
- sequence
- bill_seq
- unitprice
- quantity
- service

billing_invoices
- sequence
- invoice_number
- datetime
- sub_total

我想从billing_invoices中选择我正在使用此查询执行的特定日期范围内的所有行:

select * from billing_invoices 
where DATE(datetime) >= 'x' AND DATE(datetime) <= 'x'

但是我需要使用以下内容从adhocbills中选择等效行

billing_invoices.invoice_number = adhocbills.invoice_number

然后我需要使用:

adhocbills_lineitems中选择所有行
adhocbills.sequence = adhocbills_lineitems.bill_seq

并从adhocbills_lineitems获取总计和分组service

我希望从billing_invoices.sub_total

返回的总数

我尝试了这个查询,加入了所有表格:

SELECT 
  COUNT(i.sequence) as counter, l.service as service, SUM(i.sub_total) as sub_total, SUM(i.total_charges) as total_charges, SUM(i.vat_amount) as vat_amount, SUM(i.grand_total) as grand_total 
FROM billing_invoices i 
LEFT JOIN adhocbills a ON a.invoice_number = i.invoice_number 
LEFT JOIN adhocbills_lineitems l ON a.sequence = l.bill_seq 
WHERE 
  i.proforma <> 'Y' 
  AND i.invoice_type = 'Invoice' 
  AND a.status = 'Completed' 
  AND DATE(i.datetime) >= '2016-09-01' 
  AND DATE(i.datetime) <= '2016-09-30' 
GROUP BY l.service 
ORDER BY grand_total DESC

但是返回的值不正确

例如,我在adhocbills_lineitems表格中有这些数据,所以当这些数据按service分组时,会有2行:

Service 1 / 50
Service 2 / 30+20 = 50

示例数据:

adhocbills表:

sequence = '1'
type = 'Invoice'
invoice_number = '1234'

adhocbills

adhocbills_lineitems表:

sequence = '1'
bill_seq = '1'
unitprice = '50'
quantity = '1'
service = 'Service 1'

sequence = '2'
bill_seq = '1'
unitprice = '30'
quantity = '1'
service = 'Service 2'

sequence = '3'
bill_seq = '1'
unitprice = '20'
quantity = '1'
service = 'Service 2'

adhocbills_lineitems

billing_invoices表:

sequence = '1'
invoice_number = '1234'
sub_total = '100'
vat_amount = '20'
grand_total = '120'
datetime = '2016-09-01'
invoice_type = 'Invoice'

billing_invoices

所以从这个样本数据来看,当&#39; service&#39;列分组在adhocbills_lineitems中,结果应为:

服务1 = 50 - (由1行= 50组成) 服务2 = 50 - (由2行= 30和20组成)

1 个答案:

答案 0 :(得分:1)

您的表格结构与选择查询不匹配。此答案基于您有关表与预期输出之间关系的信息。

SELECT 
  l.service,
  SUM(l.unitprice) AS total
FROM 
  billing_invoices i
  LEFT JOIN adhocbills a ON a.invoice_number = i.invoice_number
  LEFT JOIN adhocbills_lineitems l ON a.sequence = l.bill_seq
WHERE 
  i.datetime BETWEEN '2016-09-01' AND '2016-09-30'
GROUP BY
  l.service
ORDER BY
  total DESC

这符合您的预期输出。你应该按照你在问题中提到的unitprice而不是sub_total进行求和。

如果有任何限制,请将它们添加到WHERE子句。

由于MySQL不支持表达式索引,因此我简化了日期条件,以便能够在datetime字段上使用普通索引。