我有多個表我加入。我試圖通過OrderNo將數據分組。我的結果是重複的行。如何讓我的結果全部彙總到OrderNo?SQL腳本按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
下面是數據的一個樣本:
結果應該是什麼樣子:
你想讓這些黃色的行看起來像你捲起來後的樣子嗎?例如,LoadedMiles或EmptyMiles列的值是多少?您可以發佈顯示您預期輸出的樣本結果。 – yalpertem 2014-09-03 13:43:58
您的結果不具有重複的行,每行都具有與其他列中的不同值相同的OrderId,因此您無法將它們合併在一起。 – AlexDeb 2014-09-03 13:59:13
@AlexDeb - 是的,它們是重複的行。這是相同的訂單號,總費用,linehaul,其他,總額,orderpay,perdiempay,totalpay。唯一不同的是「空里程」和「加載里程」。 – Kathy 2014-09-03 14:14:05