SQL Server:每列不同的日期过滤器

时间:2016-03-21 21:09:55

标签: sql sql-server

有没有办法过滤年份= 2014年的第一笔金额,以及年份= 2015年的第二笔金额?

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

这似乎超级简单,但是当我添加Where year(InvDate) = 2014时,我意识到我正在过滤那一年的所有结果,当我需要每行两年时。

执行Where year(InvDate) = 2014 OR year(InvDate) = 2015会给我2行,我只想要1行。

结果集应为

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

编辑:如何计算(sales_2015 - sales_2014)/ 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。计算器给了我0.05892350932。我的sales列dataType为decimal(18,2)

EDIT2:看起来我需要使用超过2个小数位来进行除法。

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

2 个答案:

答案 0 :(得分: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;

编辑:

对于评论中的问题:

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;

答案 1 :(得分: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