Sql递增计数条件值逐行

时间:2018-04-30 02:39:52

标签: sql count

n   id  Name    ShipDate    Pfit
1   1   apple   2018-04-14  +   
2   1   apple   2018-04-15  +   
3   1   apple   2018-04-16  +   
4   1   apple   2018-04-17  -   
5   1   apple   2018-04-18  -   
1   2   bread   2018-04-14  -   
2   2   bread   2018-04-15  -   
3   2   bread   2018-04-16  +   
1   3   orange  2018-04-14  +   
2   3   orange  2018-04-15  +   
3   3   orange  2018-04-16  -   
1   4   tomato  2018-04-14  +   
2   4   tomato  2018-04-15  -   
3   4   tomato  2018-04-16  -   

我想在每个项目的Pfit列中递增计数(+)或( - ),并将此结果作为序列列 我该怎么做? (这就是我想要的)(Mssql 2012)

n   id  Name    ShipDate    Pfit Serial
1   1   apple   2018-04-14  +       1
2   1   apple   2018-04-15  +       2
3   1   apple   2018-04-16  +       3
4   1   apple   2018-04-17  -       1
5   1   apple   2018-04-18  -       2
1   2   bread   2018-04-14  -       1
2   2   bread   2018-04-15  -       2
3   2   bread   2018-04-16  +       1
1   3   orange  2018-04-14  +       1
2   3   orange  2018-04-15  +       2
3   3   orange  2018-04-16  -       1
1   4   tomato  2018-04-14  +       1
2   4   tomato  2018-04-15  -       1
3   4   tomato  2018-04-16  -       2

2 个答案:

答案 0 :(得分:0)

使用此脚本:

select * 
,ROW_NUMBER() OVER(PARTITION BY [id], [Name],[Pfit] ORDER BY [ShipDate] asc)  as Serial
from TempTable

测试数据:

CREATE TABLE TempTable
    ([n] int, [id] int, [Name] varchar(6), [ShipDate] datetime, [Pfit] varchar(1))
;

INSERT INTO TempTable
    ([n], [id], [Name], [ShipDate], [Pfit])
VALUES
    (1, 1, 'apple', '2018-04-14 00:00:00', '+'),
    (2, 1, 'apple', '2018-04-15 00:00:00', '+'),
    (3, 1, 'apple', '2018-04-16 00:00:00', '+'),
    (4, 1, 'apple', '2018-04-17 00:00:00', '-'),
    (5, 1, 'apple', '2018-04-18 00:00:00', '-'),
    (1, 2, 'bread', '2018-04-14 00:00:00', '-'),
    (2, 2, 'bread', '2018-04-15 00:00:00', '-'),
    (3, 2, 'bread', '2018-04-16 00:00:00', '+'),
    (1, 3, 'orange', '2018-04-14 00:00:00', '+'),
    (2, 3, 'orange', '2018-04-15 00:00:00', '+'),
    (3, 3, 'orange', '2018-04-16 00:00:00', '-'),
    (1, 4, 'tomato', '2018-04-14 00:00:00', '+'),
    (2, 4, 'tomato', '2018-04-15 00:00:00', '-'),
    (3, 4, 'tomato', '2018-04-16 00:00:00', '-')
;

SQL Fiddlehttp://sqlfiddle.com/#!18/b60fa/1/0

希望它可以帮助你:)

答案 1 :(得分:0)

@ITWeiHan给出的答案可以假设每个id组中最多只能有一个+/-。如果可能有多个优缺点,那么我们需要做更多的工作。一种安全的方法是使用行数方法中的差异:

cte2 AS (
    SELECT *,
        ROW_NUMBER() OVER (PARTITION BY id ORDER BY n) -
        ROW_NUMBER() OVER (PARTITION BY id, Pfit ORDER BY n) rn
    FROM cte
)

SELECT n, id, name, ShipDate, Pfit,
    ROW_NUMBER() OVER (PARTITION BY id, rn ORDER BY n) AS Serial
FROM cte2
ORDER BY
    id, n;

enter image description here

Demo

请注意,我已修改您的示例数据,以便id=1有两组加号记录。