我有一个大型数据集,其销售数据类似于
***Category - Salesperson - Customer - Year - Jun - Jul .....***
Summary - Candice - R.Zeek - 2016 - $100 - $10
Summary - Candice - R.Zeek - 2017 - $40 - $50
Shirts - Candice - R.Zeek - 2016 - $80 - $10
Shirts - Candice - R.Zeek - 2017 - $40 - $50
Pants - Candice - R.Zeek - 2016 - $20 - $0
问题是在这个例子中裤子没有2017行。由于所有的销售都是2017年的衬衫。
这导致了一种情况,即如果销售人员没有针对特定类别/销售人员/客户/年份组合的任何销售数据,那么它就没有一条线。
这会使销售报告看起来很糟糕,因为不同的销售人员会有不同的行数。我想要一致性,所以如何在Jun,Jul的销售额为零或0的示例中获得2017年的一行。
添加到这篇文章。以下2个查询
Select distinct Year from @FinalResultTable
Select distinct CategorySequence, SalesPersonIdFromCustomer, CustomerNumber, Year from @FinalResultTable
生产1.不同年份的数量。在我的情况下,2015年,2016年,2017年,2018年。和2.我所需的销售数据需要额外的行
年
2015
2016
2017
2018
CategorySequence SalesPersonIdFromCustomer CustomerNumber Year
1 SP000032 C000703 2016
1 SP000032 C000703 2017
1 SP000032 C000710 2016
1 SP000032 C000710 2017
1 SP000032 C000710 2018
编辑2.
我添加了以下代码
Insert into @FinalResultTable
Select S1.CategorySequence, SRT.CategoryDescription, S2.SalesPersonIdFromCustomer, SRT.SalesPersonName, S3.CustomerNumber, SRT.CustomerName, SRT.CustomerAddress, SRT.PercentageOrAmount,
S4.Year, SRT.Jun, SRT.Jul, SRT.Aug, SRT.Sep, SRT.Oct, SRT.Nov, SRT.Dec, SRT.Jan, SRT.Feb, SRT.Mar, SRT.Apr, SRT.May,
Coalesce(SRT.Jun,0) + Coalesce(SRT.Jul,0) + Coalesce(SRT.Aug,0) + Coalesce(SRT.Sep,0) + Coalesce(SRT.Oct,0) + Coalesce(SRT.Nov,0) + Coalesce(SRT.Dec,0) +
Coalesce(SRT.Jan,0) + Coalesce(SRT.Feb,0) + Coalesce(SRT.Mar,0) + Coalesce(SRT.Apr,0) + Coalesce(SRT.May,0)
From (select distinct CategorySequence from @SelectResultTable) S1
Cross join (select distinct SalesPersonIdFromCustomer from @SelectResultTable) S2
Cross join (select distinct CustomerNumber from @SelectResultTable) S3
Cross join (select distinct year from @SelectResultTable) S4
Left join @SelectResultTable SRT on
SRT.CategorySequence = S1.CategorySequence and
SRT.SalesPersonIdFromCustomer = S2.SalesPersonIdFromCustomer and
SRT.CustomerNumber = S3.CustomerNumber and
SRT.Year = S4.Year
Select * from @FinalResultTable
Order by SalesPersonIdFromCustomer, CustomerNumber, CategorySequence, PercentageOrAmount, Year
Return
它可以工作,但问题是所有SRT列(例如类别描述)都是Null。所以我需要进行更新并再次遍历表以获取所有信息,还是可以修改插入来处理它?</ p>
答案 0 :(得分:1)
您可以使用cross join
生成行,然后加入存在的信息:
select c.Category, sp.Salesperson, t.Customer, y.Year
t.Jun, t.Jul
from (select distinct salesperson from t) sp cross join
(select distinct category c from t) c cross join
(select distinct year from t) as y left join
t
on t.salesperson = sp.salesperson and t.category = c.category and t.year = y.year;
如果您想要零而不是NULL
s,请使用COALESCE(t.Jun, 0)
作为Jun`等等。