这实际上是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
答案 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