我编写了以下语句,它返回了我要查找的数据,显示了添加到OrderNo的每个客户费用的多行。我希望合并一个子查询,它将返回FK_OrderNo的总成本(总和)。
例如,订单号4915有4个客户费用,因此在显示4个条目后,我想要一行显示总费用。请参阅下面的图片链接,了解我目前获得的结果。
http://i.stack.imgur.com/rlrH4.png
到目前为止,这是我的代码:
![Use AirTrak
SELECT PK_OrderNo
,Housebill
,OrgAirport
,DestAirport
,CallIn
,CallInName
,Description
,APARType
,Total
,TotalMiles
,OrderDate
,PODDateTime
,ShipmentDateTime
,InvoiceDateTime
From dbo.tbl_ShipmentHeader as SH
Inner Join dbo.tbl_ShipmentAPAR as SC
On SH.PK_OrderNo = SC.FK_OrderNo
where SH.BillNo = 2003 and
SC.APARCode= 'C'
答案 0 :(得分:0)
如果要使用新行,则必须在第二个查询中获取SUM。 使用UNION ALL,你可以结合2套。如果没有ALL关键字,它将在你的集合上进行DISTINCT。
DECLARE
@Bill INT = 2003;
SELECT PK_OrderNo
,Housebill
,OrgAirport
,DestAirport
,CallIn
,CallInName
,Description
,APARType
,Total
,TotalMiles
,OrderDate
,PODDateTime
,ShipmentDateTime
,InvoiceDateTime
From dbo.tbl_ShipmentHeader as SH
Inner Join dbo.tbl_ShipmentAPAR as SC
On SH.PK_OrderNo = SC.FK_OrderNo
where SH.BillNo = @Bill and
SC.APARCode= 'C'
UNION ALL
SELECT PK_OrderNo
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,SUM(Total)Total
,NULL
,NULL
,NULL
,NULL
,NULL
From dbo.tbl_ShipmentHeader as SH
Inner Join dbo.tbl_ShipmentAPAR as SC
On SH.PK_OrderNo = SC.FK_OrderNo
where SH.BillNo = @Bill and
SC.APARCode= 'C'
GROUP BY
PK_OrderNo
答案 1 :(得分:0)
你可以通过汇总进行分组!这是一个例子,不是您的数据,但我认为易于理解和可根据您的需求进行定制:
DECLARE @orders TABLE
(
orderID INT,
item VARCHAR(30),
quantity INT,
price float
)
INSERT INTO @orders
VALUES
(1,'Daiwa Aqualite Powerfloat',1,74.90),
(1,'Berkleys Firewire',220,0.12),
(1,'Cat Boilies Blood Flavour',1,6.49),
(1,'Black Cat Dead Bait Rig',2,5.00),
(2,'Shimano Alivio DX',1,69.90),
(2,'MAD Carpline',250,0.08),
(2,'Alfa Boilies 1KG Tutti Frutti',1,6.49),
(2,'Exner Strong Waggler 8g',1,5.25)
SELECT orderID,
CASE WHEN orderID IS NULL
THEN '-- GRAND TOTAL --'
ELSE COALESCE(item,'- TOTAL FOR ORDER ' + CAST(orderID AS VARCHAR(5)) + '-')
END AS item,
SUM(quantity * price) as linetotal
FROM @orders
GROUP BY ROLLUP(orderID, item);
答案 2 :(得分:0)
尝试以下查询。总量将作为结果重复的唯一因素并不是唯一的。
SELECT
PK_OrderNo,
Housebill,
OrgAirport,
DestAirport,
CallIn,
CallInName,
Description,
APARType,
Total,
TotalMiles,
OrderDate,
PODDateTime,
ShipmentDateTime,
InvoiceDateTime,
sd.total_charge
FROM (SELECT
PK_OrderNo,
SUM(charge) total_charge
FROM /*your charge table*/
GROUP BY PK_OrderNo) sd,
dbo.tbl_ShipmentHeader AS SH
INNER JOIN dbo.tbl_ShipmentAPAR AS SC
ON SH.PK_OrderNo = SC.FK_OrderNo
WHERE SH.BillNo = 2003
AND SC.APARCode = 'C'
AND charge_table.PK_OrderNo = SH.PK_OrderNo