最近在做BI所以sql任务比较多,好久没碰过sql了,记录一下。
表数据
查询结果
--环比
select c.DepartName as 部门, convert(varchar(10), c.SalesDate, 23) as 对比年月, c.Sales as 本月销售总量, d.Sales as 上月销售总量, case when d.Sales is null or d.Sales=0 then '无穷大' else cast(cast((isnull(c.Sales, 0)-isnull(d.Sales,0))*100/isnull(d.Sales, 0) as decimal(10,2)) as varchar(50))+'%' end as 环比 from SalesDetail c left join
(select a.DepartName as DepartName, a.Sales as Sales, a.SalesDate as lsSalesDate, b.SalesDate as SalesDate from SalesDetail a join SalesDetail b on a.SalesDate=DateAdd(month, -1, b.SalesDate) and a.DepartName=b.DepartName) d
on c.SalesDate=d.SalesDate and c.DepartName=d.DepartName
--同比
select c.DepartName as 部门, convert(varchar(10), c.SalesDate, 23) as 对比年月, c.Sales as 本月销售总量, d.Sales as 去年同期销售总量, case when d.Sales is null or d.Sales=0 then '无穷大' else cast(cast((isnull(c.Sales, 0)-isnull(d.Sales,0))*100/isnull(d.Sales, 0) as decimal(10,2)) as varchar(50))+'%' end as 同比 from SalesDetail c left join
(select a.DepartName as DepartName, a.Sales as Sales, a.SalesDate as lsSalesDate, b.SalesDate as SalesDate from SalesDetail a join SalesDetail b on a.SalesDate=DateAdd(year, -1, b.SalesDate) and a.DepartName=b.DepartName) d
on c.SalesDate=d.SalesDate and c.DepartName=d.DepartName
select c.DepartName as 部门,
convert(varchar(10), c.SalesDate, 23) as 对比年月,
c.Sales as 本月销售总量,
d.Sales as 去年同期销售总量,
case when d.Sales is null or d.Sales=0 then '无穷大'
else cast(cast((isnull(c.Sales, 0)-isnull(d.Sales,0))*100/isnull(d.Sales, 0) as decimal(10,2)) as varchar(50))+'%' end as 同比,
e.Sales as 上月销售总量,
case when e.Sales is null or e.Sales=0 then '无穷大'
else cast(cast((isnull(c.Sales, 0)-isnull(e.Sales,0))*100/isnull(e.Sales, 0) as decimal(10,2)) as varchar(50))+'%' end as 环比
from SalesDetail c
left join
(select a.DepartName as DepartName, a.Sales as Sales, a.SalesDate as lsSalesDate, b.SalesDate as SalesDate from SalesDetail a join SalesDetail b on a.SalesDate=DateAdd(year, -1, b.SalesDate) and a.DepartName=b.DepartName) d
on c.SalesDate=d.SalesDate and c.DepartName=d.DepartName
left join
(select a.DepartName as DepartName, a.Sales as Sales, a.SalesDate as lsSalesDate, b.SalesDate as SalesDate from SalesDetail a join SalesDetail b on a.SalesDate=DateAdd(month, -1, b.SalesDate) and a.DepartName=b.DepartName) e
on c.SalesDate=e.SalesDate and c.DepartName=e.DepartName;