【问题标题】:Generate record for groups that haven't any corresponding values为没有任何对应值的组生成记录
【发布时间】:2019-10-15 06:34:56
【问题描述】:

请考虑这个脚本:

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

这个脚本生成这个结果:

但我想要这个结果:

为那些在组中没有对应值的记录生成 0 条记录的最佳方法是什么?

【问题讨论】:

    标签: sql-server sql-server-2016


    【解决方案1】:

    使用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
    

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

      • 对不起,结果不是我想要的,而且是错误的。 Count 和 Price 列对于一个城市具有相同的值
      猜你喜欢
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      • 1970-01-01
      • 2015-08-30
      • 2018-09-03
      相关资源
      最近更新 更多