2013-05-29 97 views
0

T-SQL如果我有如下表:關於當前的銷售和以前的銷售

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) 
+2

什麼叫「秀意思上個月的數字。「你能提供一個你想要的輸出樣本嗎? –

回答

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) 
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 

演示:http://sqlfiddle.com/#!3/7a670/1