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

为没有任何相应值的组生成记录

  •  0
  • DooDoo  · 技术社区  · 5 年前

    请考虑以下脚本:

    declare @Table_City     table(CityName   varchar(50));
    declare @Table_Product      table(ProductName   varchar(50));
    declare @Table_Data     table(CityName   varchar(50), ProductName  varchar(50), [Count]    int, Price    int)
    
    insert into @Table_City values('Paris'),('London'),('Tokyo'),('Roma'),('Bern'),('Aten')
    insert into @Table_Product values('Toys'),('Shoe'),('TV'),('Radio')
    insert into @Table_Data values
        ('Paris', 'Shoe', 12, 10000),
        ('Paris', 'TV', 6, 1040),
        ('Bern', 'Radio', 1, 10),
        ('London', 'TV', 32, 21132),
        ('Roma', 'Shoe', 120, 654400),
        ('Aten', 'TV', 20, 35000),
        ('Paris', 'Radio', 17, 2000),
        ('Paris', 'Radio', 2, 300),
        ('Tokyo', 'TV', 100, 1002000),
        ('Aten', 'TV',20 ,4000 ),
        ('Bern', 'TV', 35, 5000),
        ('London', 'Radio', 70, 7000),
        ('London', 'TV',10 ,10000 ),
        ('Aten', 'Shoe',200 ,10500 ),
        ('London', 'Toys', 10, 8000),
        ('Paris', 'Toys',80 , 9000),
        ('Paris', 'Radio',50 ,75000 ),
        ('Tokyo', 'Shoe',45 ,5500 ),
        ('Roma', 'Toys',12 ,6000 ),
        ('Bern', 'Toys',50 ,4800 ),
        ('London', 'TV',40 ,8700 ),
        ('Aten', 'Toys', 80 ,2500 ),
        ('Aten', 'TV', 100 ,12500 )
    
    select CityName, ProductName , sum([count]) , sum(price)
    from @Table_Data
    group by CityName, ProductName
    order by 1, 2
    

    enter image description here

    但我想要这个结果:

    enter image description here

    为组中没有相应值的记录生成0记录的最佳方法是什么?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Squirrel    5 年前

    CROSS JOIN @Table_City 具有 @Table_Product LEFT JOIN @Table_Data

    SELECT c.CityName, p.ProductName, 
           SUM(COALESCE([Count], 0)) as [Count],
           SUM(COALESCE([Price], 0)) as [Price]
    FROM   @Table_City c
           CROSS JOIN @Table_Product p
           LEFT  JOIN @Table_Data d     ON c.CityName    = d.CityName
                                       AND p.ProductName = d.ProductName
    GROUP BY c.CityName, p.ProductName
    
        2
  •  2
  •   Ed Bangga    5 年前

    使用 isnull() , cross apply tabledata

    SELECT t1.CityName, t2.ProductName, 
           SUM(isnull(d.[Count], 0)) as [Count],
           SUM(isnull(d.[Price], 0)) as [Price]
    FROM   @Table_City t1
           CROSS JOIN @Table_Product t2
           LEFT JOIN @Table_Data d ON t1.CityName = d.CityName
                 AND d.ProductName = t2.ProductName
    GROUP BY t1.CityName, t2.ProductName
    ORDER BY t1.CityName, t2.ProductName