2017-03-06 48 views
0
SELECT a.UPC,COUNT(*) 
FROM StoreTransactions a WITH (NOLOCK) 
JOIN StoreTransactions_Expanded_UOM c 
ON a.StoreTransactionID = c.StoreTransactionID 
LEFT JOIN ProductCatalog cat 
ON a.ProductID = cat.ProductID 
LEFT JOIN ProductCatalogBase base 
ON cat.ProductCatalogID = base.ProductCatalogID 
JOIN ProductIdentifiers d 
ON cat.ProductID = d.ProductID AND d.ProductIdentifierTypeID = 2 

GROUP BY a.UPC 
, d.IdentifierValue, cat.PackDesc, a.ReportedCost, 
base.ManualHigh, base.ManualLow,cat.DateTimeCreated,cat.DateTimeLastUpdate 
ORDER BY count(*) desc 

我想統計UPC對應的UPC,但沒有得到如下的正確結果。對應的列出項目的計數項目

UPC    Count 
071990316006 1463 
026565245455 4530 
+1

你爲什麼所有這些列分組?你應該只是由a.UPC分組。爲什麼NOLOCK? http://blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere/ –

+0

同意@SeanLange。如果你只需要「UPC」的計數,那麼只需要「Group By a.UPC」。刪除「Group By」中的其他列。 –

+0

你也可以用一個'LEFT JOIN ProductCatalog cat'來連接ProductIdentifiers。這可能會給你不確定的結果。 –

回答

0

只需按a.UPC:

SELECT a.UPC,COUNT(*) 
FROM StoreTransactions a WITH (NOLOCK) 
JOIN StoreTransactions_Expanded_UOM c 
ON a.StoreTransactionID = c.StoreTransactionID 
LEFT JOIN ProductCatalog cat 
ON a.ProductID = cat.ProductID 
LEFT JOIN ProductCatalogBase base 
ON cat.ProductCatalogID = base.ProductCatalogID 
JOIN ProductIdentifiers d 
ON cat.ProductID = d.ProductID AND d.ProductIdentifierTypeID = 2 
GROUP BY a.UPC 
ORDER BY count(*) desc