如何优化此查询以返回单个产品ID及其数量总和

时间:2018-05-08 18:06:32

标签: sql sql-server sql-server-2016

这实际上是this问题的后续跟进。

以下查询生成显示的结果。如何对其进行优化,以便为每个产品ID返回单行,并将各自的数量相加。

    SELECT DISTINCT ld.ProductId, ld.Quantity,ld.UnitPrice ,
  STUFF((SELECT ',' + CAST(lh1.LandingId AS VARCHAR) FROM dbo.LandingHeaders lh1 WHERE (lh1.LandingDate  BETWEEN '20171101' AND '20171107') AND (lh1.VesselOwnerId = 42
  ) FOR XML PATH('')) ,1,1,'') AS LandingIds

  FROM LandingHeaders lh 
  JOIN LandingDetails ld ON lh.LandingId = ld.LandingId
  WHERE (lh.LandingDate BETWEEN '20171101' AND '20171107') AND (lh.VesselOwnerId = 42)
  GROUP BY ld.ProductId,lh.LandingId,ld.Quantity,ld.UnitPrice

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要SUM数量列,而不是GROUP BY。另外,使用varchar时,请始终给出明确的长度:

SELECT  ld.ProductId, 
        SUM(ld.Quantity) Quantity,
        ld.UnitPrice,
        STUFF(( SELECT ',' + CAST(lh1.LandingId AS VARCHAR(20)) 
                FROM dbo.LandingHeaders lh1 
                WHERE lh1.LandingDate  BETWEEN '20171101' AND '20171107' 
                AND lh1.VesselOwnerId = 42 FOR XML PATH('')) ,1,1,'') AS LandingIds
FROM LandingHeaders lh 
INNER JOIN LandingDetails ld 
    ON lh.LandingId = ld.LandingId
WHERE lh.LandingDate BETWEEN '20171101' AND '20171107' 
AND lh.VesselOwnerId = 42
GROUP BY ld.ProductId,
         ld.UnitPrice
;

答案 1 :(得分:0)

试试这个:

SELECT productId, SUM(quantity), MAX(unitprice)
FROM
(<your query>) as t
GROUP BY productId