一些SQL刷牙......我想为客户创造的销售额每年(2005- 2008年)汇总列表,但只会显示客户销售在以前(2005- 2007年)还没有销售在2008年销售总额:与以往的显示客户,但没有目前的销售
我已经建立了两个查询...不知道哪个更有效,但无论哪种方式,我似乎无法弄清楚如何正确地执行where子句。
任何帮助将不胜感激!
查询1:
select r.ResellerName,
(select sum(rs.SalesAmount) from FactResellerSales rs
where rs.ResellerKey = r.ResellerKey
and rs.OrderDateKey >=20050101 and rs.OrderDateKey <20060101) '2005',
(select sum(rs.SalesAmount) from FactResellerSales rs
where rs.ResellerKey = r.ResellerKey
and rs.OrderDateKey >=20060101 and rs.OrderDateKey <20070101) '2006',
(select sum(rs.SalesAmount) from FactResellerSales rs
where rs.ResellerKey = r.ResellerKey
and rs.OrderDateKey >=20070101 and rs.OrderDateKey <20080101) '2007',
(select sum(rs.SalesAmount) from FactResellerSales rs
where rs.ResellerKey = r.ResellerKey
and rs.OrderDateKey >=20080101 and rs.OrderDateKey <20090101) '2008'
From DimReseller r
order by r.ResellerName ASC
查询2:
Select r.ResellerName,
SUM(case when OrderDateKey>=20050101 and OrderDateKey<20060101 then rs.SalesAmount else 0 end) '2005',
SUM(case when OrderDateKey>=20060101 and OrderDateKey<20070101 then rs.SalesAmount else 0 end) '2006',
SUM(case when OrderDateKey>=20070101 and OrderDateKey<20080101 then rs.SalesAmount else 0 end) '2007',
SUM(case when OrderDateKey>=20080101 and OrderDateKey<20090101 then rs.SalesAmount else 0 end) '2008'
from DimReseller r
inner join FactResellerSales rs on rs.ResellerKey = r.ResellerKey
Group by r.ResellerName
Order by ResellerName ASC
'2008'= 0将始终为假。没有记录将返回此查询。你正在检查字符串'2008'是否等于0.如果你想这样做删除单引号。 – Jeffrey
年,我试过2008 = 0和'2008'= 0无效... – user3221111
杰弗里,感谢您的帮助,不确定您的查询是否正在做我想做的事(我是逆向工程)...但最终想要显示的客户,2008年没有销售,但销售前几年...... – user3221111