根据一组条件获取基于最后一行和当前行的值

时间:2016-02-15 14:23:52

标签: sql sql-server

我需要根据列类型的计算条件在升级列中获取数量值,然后比较不同列组的上一年。我正在使用SQL Server 2012.

获取升级数量值列的条件是:

if previous t1 in Quantity >0 and 
(current year t2 in Quantity - previous year t1 in Quantity )>= 0,
then  
 upgrade = previous year t1 in Quantity  
 else if    
 previous year t1 in Quantity > 0 and current year t2 in Quantity - previous year t1 in Quantity <0
  then   
update =  current year t2 in Quantity

组,年份,类型,数量中的值位于表格中。所需的输出值位于“升级”列中(“升级”列中的值是我需要的输出结果)。

Group Year Type Quantity   Upgrade
a     2013  t1  2   
a     2014  t1  1
a     2014  t2  3          2
a     2015  t1  5
a     2015  t2  10
a     2016  t1  6
a     2016  t2  4          4
a     2017  t2  7          6
b     2013  t1  3
b     2014  t2  5          3
b     2015  t2  9
b     2016  t1  4
b     2016  t2  7
c     2012  t1  4
c     2012  t2  5
c     2013  t1  5
c     2013  t2  6          4
c     2014  t2  1          1  

以下是用于创建查询数据的表格

CREATE TABLE [MyTable](
[MyGroup] [nvarchar](10) NULL,
[MyYear] [nvarchar](10) NULL,
[Type] [nvarchar](10) NULL,
[Quantity] [int] NULL
)


Insert into MyTable (MyGroup, MyYear, Type, Quantity) 
 values
('a',   '2013', 't1',   '2'),
('a',   '2014', 't1',   '1'),
('a',   '2014', 't2',   '3'),
('a',   '2015', 't1',   '5'),
('a',   '2015', 't2',   '10'),
('a',   '2016', 't1',   '6'),
('a',   '2016', 't2',   '4'),
('a',   '2017', 't2',   '7'),
('b',   '2013', 't1',   '3'),
('b',   '2014', 't2',   '5'),
('b',   '2015', 't2',   '9'),
('b',   '2016', 't1',   '4'),
('b',   '2016', 't2',   '7'),
('c',   '2012', 't1',   '4'),
('c',   '2012', 't2',   '5'),
('c',   '2013', 't1',   '2'),
('c',   '2013', 't2',   '6'),
('c',   '2014', 't2',   '1');

1 个答案:

答案 0 :(得分:2)

所以,如果我理解正确,你可以这样做:

SELECT t.*,
       CASE WHEN s.quantity is null then null 
           ELSE CASE WHEN s.quantity > 0 and t.quantity - s.quantity > 0 then s.quantity
               ELSE CASE WHEN s.quantity > 0 and t.quantity - s.quantity < 0 then t.quantity end end end as 'UPGRADE'
from YourTable t
LEFT OUTER JOIN YourTable s ON(t.group = s.group and t.year = s.year-1 
                               AND t.type = 't2' and s.type = 't1')

这基本上通过使用CASE表达式来实现你想要的,类似于if,elseif,else ..