由于第三个表连接,使用左连接的SQL脚本返回重复的行

时间:2014-08-26 14:21:08

标签: sql

我希望所有订单的发货日期07/01 - 07/31来自Orders表。我加入Billing_History表来获取交付日期和我想要的其他字段。

现在我想从Drs_Settle_Hist表加入我的结算数据。这个表显示了一个订单的多行,我单独尝试了一个查询分组。

如何将按Drs_Settle_Hist分组的个人Order_ID数据插入我的查询?

Drs_Settle_Hist返回多行的查询:

SELECT     orders.id, billing_history.delivery_date, orders.revenue_code_id,  orders.bill_distance, orders.freight_charge, 
orders.otherchargetotal, orders.total_charge, billing_history.distance, billing_history.linehaul_chg, billing_history.other_charge, 
billing_history.total_charges, billing_history.tractor_id, drs_settle_hist.order_id, drs_settle_hist.order_pay, 
drs_settle_hist.perdiem_pay, drs_settle_hist.total_pay, drs_settle_hist.check_number, drs_settle_hist.pay_date 
from orders

left join billing_history ON orders.id = billing_history.order_id
left join drs_settle_hist on orders.id = drs_settle_hist.order_id


WHERE     orders.ordered_date  between '2013-01-01 00:00:00.000' and '2014-07-31 23:59:59.000' and billing_history.delivery_date 
between '2014-07-01 00:00:00.000' and '2014-07-31 23:59:59.000' and drs_settle_hist.is_void = 'N' 

此查询适用于按order_id分组:

Select drs_settle_hist.order_id, sum(drs_settle_hist.order_pay) as OrderPay,sum(drs_settle_hist.perdiem_pay) as PerDiemPay, sum(drs_settle_hist.total_pay) as TotalPay 
from drs_settle_hist where drs_settle_hist.delivery_date between '2014-07-01 00:00:00.000' and '2014-07-31 23:59:59.000' 
group by order_id

我在哪里以及如何将其纳入原始查询?

1 个答案:

答案 0 :(得分:0)

您可以将联接替换为drs_settle_hist,并将该联接更改为该表上的分组查询,并将每个order_id的所有金额相加。像这样:

SELECT     
  orders.id, 
  billing_history.delivery_date, 
  orders.revenue_code_id,  
  orders.bill_distance, 
  orders.freight_charge, 
  orders.otherchargetotal, 
  orders.total_charge, 
  billing_history.distance, 
  billing_history.linehaul_chg, 
  billing_history.other_charge, 
  billing_history.total_charges, 
  billing_history.tractor_id, 
  settle_hist.order_id, 
  settle_hist.order_pay, 
  settle_hist.perdiem_pay, 
  settle_hist.total_pay, 
  settle_hist.check_number, 
  settle_hist.pay_date 
FROM orders
LEFT JOIN billing_history ON orders.id = billing_history.order_id
LEFT JOIN (SELECT  
             order_id, 
             sum(drs_settle_hist.order_pay) as OrderPay,
             sum(drs_settle_hist.perdiem_pay) as PerDiemPay, 
             sum(drs_settle_hist.total_pay) as TotalPay,
             check_number,
             pay_date
           FROM drs_settle_hist
           GROUP BY order_id) settle_hist ON orders.id = settle_hist.order_id
WHERE     
  orders.ordered_date between '2013-01-01 00:00:00.000' and '2014-07-31 23:59:59.000'
  and billing_history.delivery_date between '2014-07-01 00:00:00.000' and '2014-07-31 23:59:59.000' 
  and drs_settle_hist.is_void = 'N' 

N.B。这假设您在工作查询中未包含的两列(check_numberpay_date)在每个order_id的多行中并不唯一