2016-03-21 4 views
0

年= 2014の最初の合計と、年= 2015の2番目の合計をフィルタリングする方法はありますか?SQL Server:列ごとに異なる日付フィルタ

Select productName, sum(sales), sum(sales) 
From Invoices 
Where productName = ? 

それは超簡単なようだが、私はWhere year(InvDate) = 2014を追加した瞬間は、私は、行ごとに両方の年を必要とするとき、私は、その年のすべての結果をフィルタリングしています実現。

Where year(InvDate) = 2014 OR year(InvDate) = 2015を実行すると2行、私は1行しか必要ありません。/sales_2014

SELECT vendorpn, (sum(case when year(InvDate) = 2015 then sales else 0 end) - sum(case when year(InvDate) = 2014 then sales else 0 end))/ 
       sum(case when year(InvDate) = 2015 then sales else 0 end) 
     from BG_Invoice a inner join BG_Parts b on a.material = b.material 
     where customer = 10011484 and vendorpn = 'LM321-118V' 
     group by vendorpn 
     having sum(sales) > 0 

は私に0.055644を与えている - どのように計算するために(sales_2014 sales_2015):

結果セットは

ProductName | sum of 2014 sales for this product | sum of 2015 sales for this product 

EDITでなければなりません。電卓は私に0.05892350932を与えています。私のsales列のデータ型はdecimal(18,2)

EDIT2です。私は除算に小数点以下2桁を使用する必要があります。

(CONVERT(DECIMAL(18,8),sum(case when year(InvDate) = 2015 then sales else 0 end)) 

答えて

3

あなたは条件付き集計でこれを行うことができます。

Select productName, 
     sum(case when year(InvDate) = 2014 then sales else 0 end) as sales_2014, 
     sum(case when year(InvDate) = 2015 then sales else 0 end) as sales_2015 
from Invoices 
group by productName; 

EDIT:

Select productName, 
     (sum(case when year(InvDate) = 2015 then sales else - sales end)/
     sum(case when year(InvDate) = 2014 then sales end) 
     ) as ratio 
from Invoices 
where year(InvDate) in (2014, 2015) 
group by productName; 
+0

美しい、受け入れます。 –

+0

簡単な質問ですが、私の本当の目標は '(sales_2015 - sales_2014)/ sales_2014'です。どのように私はそれを得るだろうか?私が編集で試したものを投稿する。 –

0

あなたのコメントに答えるためにあなたが使用することができます。

コメントでの質問にはWITHを使用してクエリを実行している仮想テーブル

ここに文:

WITH CTE as (
Select productName, 
     sum(case when year(InvDate) = 2014 then sales else 0 end) as sales_2014, 
     sum(case when year(InvDate) = 2015 then sales else 0 end) as sales_2015 
from Invoices 
group by productName; 
) 
SELECT productName, ((sales_2014 - sales_2015)/sales_2014) as result 
FROM CTE 
関連する問題