0

次のテーブルがある場合:

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

2 に答える 2

0

目的の出力に応じて、次の解決策のいずれかが機能するはずです。私はおそらく2番目の解決策にもっと傾くでしょうが、それはすべてあなたが見たいものに依存します:

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

于 2013-05-30T14:42:24.443 に答える
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)
于 2013-05-29T19:21:58.150 に答える