代码之家  ›  专栏  ›  技术社区  ›  developer

将SQL中的行与特定逻辑合并

  •  0
  • developer  · 技术社区  · 4 年前

    我有下表:

    产品类别 数量 价格
    木材 2. 40
    金属 2. 20
    玻璃 2. 40
    另外 2. 30
    杂项 3. 10
    额外的 5. 20

    我想将其他、杂项和额外类别合并为“其他”类别。数量和价格可以有其他、其他和额外类别的总和。

    产品类别 数量 价格
    木材 2. 40
    金属 2. 20
    玻璃 2. 40
    额外的 10(即2+3+5) 60(即30+10+20)

    其中一种方法是:

    -- Create temp table to hold sum of Other, Misc, Extra
    
    DECLARE @Qty AS INT, @Price AS INT
    
    SELECT @Qty = Sum(Qty), @Price = Sum(Price) 
    FROM Product 
    WHERE ProductCategory IN ('Other', 'Extra', 'Misc')
    
    DELETE FROM Product 
    WHERE ProductCategory IN ('Other', 'Extra', 'Misc')
    
    INSERT INTO Product (ProductCategory, Qty, Price) 
    VALUES ('Extra', @Qty , @Price)
    

    使用SQL最简单的方法是什么?

    0 回复  |  直到 4 年前
        1
  •  2
  •   Stu    4 年前

    您可以使用 案例外部参照 具有 group by

    select v.ProductCategory, Sum(qty) Qty, Sum(price) Price
    from t
    cross apply (values(
        case when productcategory in ('Misc','Extra') then 'Other' /*or Extra...?*/
        else ProductCategory 
      end)
    )v(ProductCategory)
    group by v.ProductCategory
    

    Example fiddle

        2
  •  1
  •   Serg    4 年前

    对临时表使用OUTPUT

    declare @tmp table(Qty int, Price int);
    
    delete tbl
      output deleted.qty, deleted.price into @tmp (Qty, Price)
    where ProductCategory in ('Misc','Other');
    
    update t
      set Qty = t.Qty + u.qty , Price = t.Price + u.Price
    from tbl t
    join (select sum(Qty) qty, sum(Price) Price
          from @tmp) u
          on t.ProductCategory = 'Extra';
    

    db<>fiddle