2011-08-11 57 views
1

彙總數據基本上我需要一羣獨特的產品數據爲一行時:SQL建議 - 爲特定的情況下

  • 供應商SKU匹配
  • 價格的產品相媲美(或)1產品線等於'0.00'

下面是一個示例數據集集以及我正在嘗試完成的工作查詢。我不完全清楚這是執行此查詢的最佳方式。

DECLARE @Test TABLE 
(
SupplierSKU VARCHAR(25), 
Description VARCHAR(50), 
Quantity VARCHAR(25), 
Price VARCHAR(25) 
) 

INSERT INTO @Test 
SELECT '123', 'APPLES', '15', '0.00' 
INSERT INTO @Test 
SELECT '124', 'ORANGES', '10', '15.34' 
INSERT INTO @Test 
SELECT '123', 'APPLES', '5', '27.40' 
INSERT INTO @Test 
SELECT '125', 'PLUMS', '67', '34.86' 
INSERT INTO @Test 
SELECT '124', 'ORANGES', '10', '15.78' 
INSERT INTO @Test 
SELECT '125', 'PLUMS', '3', '34.86' 


SELECT SupplierSKU, Description, SUM(Quantity) AS [Quantity], MAX(Price) AS [Price] 
FROM 
(
    SELECT SupplierSKU, Description, SUM(CAST(Quantity AS INT)) AS [Quantity], (SELECT MAX(CAST(Price AS MONEY)) AS [Price] FROM @Test ti WHERE ti.SupplierSKU = t.SupplierSKU AND ti.Price = t.price AND ti.Price <> '0.00') AS [Price] 
    FROM @Test t 
    GROUP BY SupplierSKU, Description, Price 
) pdata 
GROUP BY pdata.SupplierSKU, pdata.Description 

期望的結果:

SupplierSKU Description Quantity Price 
123   APPLES   20  27.40 
124   ORANGES   10  15.34 
124   ORANGES   10  15.78 
125   PLUMS   70  34.86 
+1

假設'APPLES'還有另一行價格爲'10.00'。你想要'27 .40'還是'10.00'包含15'0.00'蘋果?你會如何決定?我認爲您當前的查詢甚至不會按SKU/Price對這種情況進行正確分組。 –

+0

謝天謝地,系統不會產生這樣的數據。新的'APPLES'行將有不同的SupplierSKU。 – Jesse

+1

橘子應該返回10/15.78?或20/15.78?你提到的價格應該匹配(或0) –

回答

1

首先我修好自己的解決方案

SELECT SupplierSKU, Description, SUM(Quantity) AS [Quantity], MAX(cast(Price as money)) AS [Price] 
FROM 
( 
    SELECT SupplierSKU, Description, SUM(CAST(Quantity AS INT)) AS [Quantity], 
    (SELECT MAX(cast(PRICE as money)) from @test 
    where t.SupplierSKU = SupplierSKU and Description = t.Description and (t.price = '0.00' or t.price = price)) price 
    FROM @Test t 
    GROUP BY SupplierSKU, Description , price 
) pdata 
GROUP BY pdata.SupplierSKU, pdata.Description , price 

然後我改寫了您的解決方案更具可讀性

SELECT suppliersku, description, sum(cast(quantity as int)) quantity, max(cast(price as money)) price FROM (
SELECT suppliersku, description, quantity, price FROM @test 
WHERE price <> '0.00' 
UNION ALL 
SELECT t1.suppliersku, t1.description, t1.quantity, max(t2.price) 
FROM @test t1 
join 
@test t2 ON t1.SupplierSKU=t2.SupplierSKU and t1.Description = t2.Description 
WHERE t1.price = '0.00' 
GROUP BY t1.suppliersku, t1.description, t1.quantity 
) a 
GROUP BY suppliersku, description, price 

您可能會注意到,我得到的蘋果(15 + 5的正確的數量= 20)

+0

非常有幫助,謝謝 – Jesse

0
SELECT SupplierSKU, Description, SUM(Quantity) AS Qte, SUM(Price) AS Total 
FROM @test t 
GROUP BY SupplierSKU, Description 
ORDER BY SupplierSKU 

這是否讓你你想要什麼?

2

這應該會產生「所需的輸出」,但所需的輸出與文本目標不一致。爲什麼是數量和價格varchar。此解決方案假定您將數量轉換爲SQL表上的整數。

SELECT SupplierSKU, Description, SUM(Quantity), P AS [Price] 
    FROM @test 
    Where [Price] > 0 
    GROUP BY SupplierSKU, Description, Price 
+0

謝謝Balam。這正是我所期待的。爲什麼「數量」和價格「varchar」是一個非常好的問題,我很樂意問我目前系統的架構師...... – Jesse