刷新一些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
答案 0 :(得分:1)
只需将查询2用作内部查询,并选择2008年为零的位置:
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) x
Having SUM(case when OrderDateKey>=20080101 and OrderDateKey<20090101 then rs.SalesAmount else 0 end) = 0
Order by ResellerName ASC
'2008'列始终为0,因此您不需要它,或者可以用常量0
替换它:
select
...
0 as '2008'
...
如果你愿意的话。
答案 1 :(得分:0)
应该容易吗?只需在子选择中选择2008年没有Sales的resellerkeys并将它们连接到FactResellerSales?
SELECT rs.*
FROM FactResellerSales rs
JOIN (SELECT DISTINCT r.ResellerKey
FROM FactResellerSales
WHERE OrderDateKey < 20080101) r on rs.ResellerKey = r.ResellerKey
更新
SELECT r.ResellerName,
sum(rs.SalesAmount) AS SalesAmount
YEAR(convert(date,CONVERT(varchar(10),rs.OrderDateKey,101))) AS SALES_YEAR
FROM DimReseller r
INNER JOIN (SELECT rs.SalesAmount,
rs.Resellerkey,
rs.OrderDateKey
FROM FactResellerSales rs
INNER JOIN (SELECT DISTINCT a.ResellerKey
FROM FactResellerSales
WHERE OrderDateKey < 20080101) a on rs.ResellerKey = a.ResellerKey) sub on r.Resellerkey = sub.Resellerkey
GROUP BY r.ResellerName
ORDER BY r.ResellerName ASC