2016-05-11 10 views
0

過去24ヶ月の売上を月別に報告したい。次の月には25ヵ月の数字が報告書から外れ、最後の24ヵ月を再度反映するはずです。私は年の変更を処理するためにクエリを書く方法がわかりません。ここに私が持っているものがあります。where節が現在の年の結果を複数回返すmonth()を使用して24ヶ月の販売履歴を返すクエリ

select [Amount] * -1 as 'Parts Not Sold On Service Order Current', 0 as 'Parts Sold  On Service Order', [Document Date] 
from [G_L Entry] 
where [G_L Account No_] between '40000' and '49999' 
and  [Dimension code] = 'par' 
and  [Document No_] not like 'PSV%' 
AND  YEAR([Document Date]) = YEAR(CURRENT_TIMESTAMP) 
AND  MONTH([Document Date]) = MONTH(CURRENT_TIMESTAMP) 

union 

    select [Amount] * -1 as 'Parts Not Sold On Service Order Current -1', 0 as 'Parts Sold  On Service Order', [Document Date] 
from [G_L Entry] 
where [G_L Account No_] between '40000' and '49999' 
and  [Dimension code] = 'par' 
and  [Document No_] not like 'PSV%' 
AND  YEAR([Document Date]) = YEAR(CURRENT_TIMESTAMP) 
AND  MONTH([Document Date]) = MONTH(CURRENT_TIMESTAMP) -1 

union 

    select [Amount] * -1 as 'Parts Not Sold On Service Order Current -2', 0 as 'Parts Sold  On Service Order', [Document Date] 
from [G_L Entry] 
where [G_L Account No_] between '40000' and '49999' 
and  [Dimension code] = 'par' 
and  [Document No_] not like 'PSV%' 
AND  YEAR([Document Date]) = YEAR(CURRENT_TIMESTAMP) 
AND  MONTH([Document Date]) = MONTH(CURRENT_TIMESTAMP) -2 

これにより、前年に入ってから同じ年の結果が繰り返されます。月は、前年度からわずか5ヶ月です。翌月は6ヶ月になります。これを処理するクエリを作成するにはどうすればよいですか?

答えて

1

あなたがあなたのWHERE文に以下を追加してみてください、すでに他のすべての側面でそれを望むように働くあなたのクエリを持っていると仮定すると:

AND DateDiff(Month, [Document Date], CURRENT_TIMESTAMP) < 24 

あなたはそれを得るためにそれを少しプレイしていることちょうどあなたの特定のレポート(例えば、「< 23」、「< 25」など)

のために私は心読者ないんだけど、あなたの現在のWHERE声明にこれを統合することは、あなたが何をしたいあなたを与えると短くなる場合がありあなたのお問い合わせはunionを除きます:

select [Amount] * -1 as 'Parts Not Sold On Service Order Current', 0 as 'Parts Sold On Service Order', [Document Date] 
from [G_L Entry] 
where [G_L Account No_] between '40000' and '49999' 
and  [Dimension code] = 'par' 
and  [Document No_] not like 'PSV%' 
AND  DateDiff(Month, [Document Date], CURRENT_TIMESTAMP) < 24 
+0

ブーム!!完璧。私は、レポートソフトウェア内の数ヶ月を壊すことができます。ありがとう。私は日時関数についてもっと学びたいと思っています。ここや他の場所にある良い記事をお勧めしますか? –

+1

@Craig Zirnheld、申し訳ありませんが、良いチュートリアルスタイルのものは分かりません。私は99%の時間のSQL Server型の質問について[MSDN](https://msdn.microsoft.com/en-us/library/ms186724.aspx)を読んだだけです。 – Sturgus

関連する問題