确保仅显示不同的产品ID

时间:2016-01-20 16:32:10

标签: sql sql-server-2014-express

考虑从该查询生成的以下部分结果集(从在ssms中创建视图派生而来)。

SELECT DISTINCT TOP (100) PERCENT 
    dbo.LandingHeaders.VesselId, dbo.LandingDetails.ProductId, 
    SUM(dbo.LandingDetails.Quantity) AS Quantity, 
    dbo.LandingDetails.UnitPrice
FROM
    dbo.LandingDetails 
INNER JOIN
    dbo.LandingHeaders ON dbo.LandingDetails.LandingId = dbo.LandingHeaders.LandingId 
INNER JOIN
    dbo.Vessels ON dbo.LandingHeaders.VesselId = dbo.Vessels.VesselId
GROUP BY 
    dbo.LandingHeaders.VesselId, dbo.LandingDetails.UnitPrice, 
    dbo.LandingDetails.ProductId, dbo.LandingHeaders.LandingDate1
HAVING        
   (dbo.LandingHeaders.LandingDate1 BETWEEN CONVERT(DATETIME, '2016-01-06 00:00:00', 102) 
                                    AND CONVERT(DATETIME, '2016-01-13 00:00:00', 102))
ORDER BY 
    dbo.LandingHeaders.VesselId, dbo.LandingDetails.ProductId

enter image description here

我想让它只返回不同的ProductId及其相关数量的总和。

修改

例如,在容器Id为4的那些条目中,有三条线,其中ProductId为22.理想情况下,我希望它返回以下单行,

4    22    19.1   0.4

到目前为止,我最接近的是如下。

SELECT DISTINCT 
    ld.ProductId, 
    ROUND(SUM(ld.Quantity), 2) AS Quantity,
    ld.UnitPrice, lh.VesselId 
FROM 
    LandingDetails ld 
JOIN 
    LandingHeaders lh ON ld.LandingId = lh.LandingId
GROUP BY 
    ld.ProductId, ld.UnitPrice, lh.VesselId
WHERE 
    lh.LandingDate1 BETWEEN '20160106' AND '20160113'

显然不够接近。我欢迎你提出建议。

1 个答案:

答案 0 :(得分:1)

您不需要DISTINCTGROUP BY应该为您完成这项工作。

WHEREGROUP BY

之前
SELECT  DISTINCT ld.ProductId, 
        ROUND(SUM(ld.Quantity),2) AS Quantity,
        ld.UnitPrice, 
        lh.VesselId 
FROM LandingDetails ld 
JOIN LandingHeaders lh 
  ON ld.LandingId = lh.LandingId
WHERE lh.LandingDate1 BETWEEN '20160106' AND '20160113'
GROUP BY ld.ProductId, ld.UnitPrice, lh.VesselId