SQL建议 - 为特定情况汇总数据

时间:2011-08-11 15:17:46

标签: sql-server-2005 tsql

基本上,我需要在以下情况下将唯一的产品数据分组到一行:

  • 供应商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

3 个答案:

答案 0 :(得分:2)

这应该产生“期望的输出”,但是期望的输出与文本目标不一致。为什么数量和价格变化。此解决方案假定您在SQL表上将数量转换为整数。

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

答案 1 :(得分: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)

答案 2 :(得分:0)

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

这会让你得到你想要的吗?