如果我有下表:
CREATE TABLE [dbo].[Sales](
[SaleDate] [datetime] NULL,
[SaleAmt] [money] NULL
) ON [PRIMARY]
我如何按月检索销售总额,还会显示上个月的数据。
我认为以下内容可行,但不会
select
DATEPART(m,s1.saledate), SUM(s1.SaleAmt), SUM(s2.SaleAmt)
from
sales s1
inner join
Sales s2 on DATEPART(m, DateAdd(m, -1, s2.saledate)) = DATEPART(m, s1.saledate)
group by
DATEPART(m, s1.saledate)
答案 0 :(得分:0)
我认为我提出了一个非常简单的解决方案,尽管我认为它不如使用自连接方法那么好
select DATEPART(m,s1.saledate) as Month,
SUM(s1.SaleAmt) as CurrentSales,
(select SUM(SaleAmt)
from Sales where DATEPART(m,saledate)=DATEPART(m,s1.saledate)-1) as PreviousSales from
sales s1
group by DATEPART(m,s1.saledate)
答案 1 :(得分:0)
根据您所需的输出,以下解决方案之一应该适合您。我可能更倾向于第二种解决方案,但这一切都取决于你想看到的内容:
select
s2.month as 'C-MONTH',
s1.month as 'P-MONTH',
s2.amt as 'C-AMT',
s1.amt as 'P-AMT'
from
(
select
datepart(m, saledate) as month,
sum(SaleAmt) as amt
from
Sales
group by
datepart(m, saledate)
) s1,
(
select
datepart(m, saledate) as month,
sum(SaleAmt) as amt
from
Sales
group by
datepart(m, saledate)
) s2
where
s2.month = s1.month + 1
演示:http://sqlfiddle.com/#!3/66ad9/1
select
s2.month as 'C-MONTH',
s1.month as 'P-MONTH',
s2.amt as 'C-AMT',
s1.amt as 'P-AMT'
from
(
select
datepart(m, saledate) as month,
sum(SaleAmt) as amt
from
Sales
group by
datepart(m, saledate)
) s1
right outer join
(
select
datepart(m, saledate) as month,
sum(SaleAmt) as amt
from
Sales
group by
datepart(m, saledate)
) s2
on
s2.month = s1.month + 1