我加入了多个表格。我正在尝试通过OrderNo将数据分组。我的结果是重复行。如何将所有结果汇总到OrderNo?
SELECT
tractor.id as Unit,
tractor.type_of,
orders.id as OrderNo,
billing_history.delivery_date,
orders.total_charge,
Case when movement.loaded = 'L' then movement.move_distance else 0 end as LoadedMiles,
Case when movement.loaded = 'E' then movement.move_distance else 0 end as EmptyMiles,
billing_history.distance,
billing_history.linehaul_chg,
billing_history.other_charge,
billing_history.total_charges,
OrderPay,
PerDiemPay,
TotalPay
from tractor
Left join billing_history
on billing_history.tractor_id = tractor.id
Left join orders
ON billing_history.order_id = orders.id
Left join
(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.is_void = 'N'
group by
drs_settle_hist.order_id)
drs_settle_hist on orders.id = drs_settle_hist.order_id
Left join movement_order
on billing_history.order_id = movement_order.order_id
Left join movement
on movement_order.movement_id = movement.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 tractor.type_of is not null
以下是数据示例:
结果应如何:
答案 0 :(得分:0)
我认为Distinct关键字可能对您有用,例如Distinct(orders.id)。
答案 1 :(得分:-1)
您只是在联接中对子选择进行分组。尝试对完整查询进行分组:
SELECT
tractor.id as Unit,
tractor.type_of,
orders.id as OrderNo,
billing_history.delivery_date,
orders.total_charge,
Case when movement.loaded = 'L' then movement.move_distance else 0 end as LoadedMiles,
Case when movement.loaded = 'E' then movement.move_distance else 0 end as EmptyMiles,
billing_history.distance,
billing_history.linehaul_chg,
billing_history.other_charge,
billing_history.total_charges,
OrderPay,
PerDiemPay,
TotalPay
from tractor
Left join billing_history
on billing_history.tractor_id = tractor.id
Left join orders
ON billing_history.order_id = orders.id
Left join
(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.is_void = 'N'
group by
drs_settle_hist.order_id)
drs_settle_hist on orders.id = drs_settle_hist.order_id
Left join movement_order
on billing_history.order_id = movement_order.order_id
Left join movement
on movement_order.movement_id = movement.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 tractor.type_of is not null
group by OrderNo