2012-05-07 94 views
0

我現在的SQL查詢:返回如何根據另一列獲取一列的總和?

SELECT WorkOrderParts.PartQTY, 
     '$' + CONVERT(varchar(22), WorkOrderParts.PartCost, 1) AS PartCost, 
     '$' + CONVERT(varchar(22), WorkOrderParts.PartQTY * WorkOrderParts.PartCost, 1) AS PartsTotal, 
     tblParts.fldMfgPartNumber 
FROM tblWorkorders 
INNER JOIN WorkOrderParts ON tblWorkorders.ID = WorkOrderParts.WorkOrderId 
INNER JOIN tblParts ON WorkOrderParts.PartId = tblParts.ID 
WHERE (tblWorkorders.ProcessedDate BETWEEN '5/1/2012 12:00:00 AM' 
             AND '5/2/2012 12:00:00 AM') 
GROUP BY tblWorkorders.ProcessedDate, WorkOrderParts.PartCost, 
     WorkOrderParts.PartQTY, tblParts.fldMfgPartNumber, tblWorkorders.ID 
ORDER BY tblParts.fldMfgPartNumber 

數據:

PartQTY PartCost PartsTotal fldMfgPartNumber 
------- -------- ---------- ---------------- 
1  $48.71 $48.71  1878042C91 
1  $48.71 $48.71  1878042C91 
1  $48.71 $48.71  1878042C91 
1  $11.82 $11.82  1R1804 
1  $11.82 $11.82  1R1804 
1  $11.82 $11.82  1R1804 
4  $255.39 $1,021.56 2697041 
1  $8.94  $8.94  3719 

如何修改我的SQL查詢返回的結果如下:

PartQTY PartCost PartsTotal fldMfgPartNumber 
------- -------- ---------- ---------------- 
3  $48.71 $146.13  1878042C91 
3  $11.82 $35.46  1R1804 
4  $255.39 $1,021.56 2697041 
1  $8.94  $8.94  3719 
+0

您需要將tblWorkorders.ProcessedDate從組中取出,我想。這些可能是獨特的。刪除它會正確分組你的結果(我認爲) – MikeTWebb

回答

0

你的意思是類似於GROUP BY st atement?

select sum(PartQTY), avg(PartCost), sum(PartsTotal), fldMfgPartNumber from Table group by fldMfgPartNumber

0

假設tblParts.fldMfgPartNumber是你想按組(我猜是 - 基於1998年預期的結果集)列,那麼你可以嘗試這樣的:

SELECT SUM(WorkOrderParts.PartQTY), 
    '$' + CONVERT(VARCHAR(22), MIN(WorkOrderParts.PartCost), 1) AS PartCost, 
    '$' + CONVERT(VARCHAR(22), SUM(WorkOrderParts.PartQTY * WorkOrderParts.PartCost), 1) AS PartsTotal, 
    tblParts.fldMfgPartNumber 
FROM tblWorkorders 
INNER JOIN WorkOrderParts ON tblWorkorders.ID = WorkOrderParts.WorkOrderId 
INNER JOIN tblParts ON WorkOrderParts.PartId = tblParts.ID 
WHERE (tblWorkorders.ProcessedDate BETWEEN '5/1/2012 12:00:00 AM' AND '5/2/2012 12:00:00 AM') 
GROUP BY tblParts.fldMfgPartNumber; 
0
SELECT SUM(WorkOrderParts.PartQTY) as PartQTY, '$' + CONVERT(varchar(22), 
     WorkOrderParts.PartCost, 1) AS PartCost, '$' + CONVERT(varchar(22), 
     WorkOrderParts.PartQTY * WorkOrderParts.PartCost, 1) AS PartsTotal, 
     tblParts.fldMfgPartNumber 
FROM tblWorkorders 
INNER JOIN WorkOrderParts ON tblWorkorders.ID = WorkOrderParts.WorkOrderId 
INNER JOIN tblParts ON WorkOrderParts.PartId = tblParts.ID 
WHERE (tblWorkorders.ProcessedDate BETWEEN '5/1/2012 12:00:00 AM' 
             AND '5/2/2012 12:00:00 AM') 
GROUP BY tblWorkorders.ProcessedDate, WorkOrderParts.PartCost, 
     tblParts.fldMfgPartNumber, tblWorkorders.ID 
ORDER BY tblParts.fldMfgPartNumber 
相關問題