2016-01-20 36 views
0

考慮從此查詢中產生的以下部分結果集(從在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

我想這僅返回不同的產品編號的和他們的相關量的總和。

EDIT

例如在這些條目,其中所述容器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' 

這顯然不夠接近。我很歡迎你的建議。

+0

你可以包括你的樣本數據和慾望輸出之前? –

+0

@JuanCarlosOropeza請參閱我添加到問題中的編輯。發佈實際數據有點困難。 –

+0

你從你試過的查詢中得到什麼?你得到的結果有什麼問題? –

回答

1

你不需要DISTINCT,GROUP 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