如何根据另一列获得一列的SUM?

时间:2012-05-07 22:05:27

标签: sql sum

我当前的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

3 个答案:

答案 0 :(得分:0)

你的意思是GROUP BY声明吗?

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

答案 1 :(得分:0)

假设tblParts.fldMfgPartNumber是您想要分组的列(我猜 - 基于您期望的结果集),那么您可以尝试类似:

    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;

答案 2 :(得分: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