我正在尝试将多种条件考虑在我正在使用的数据集中。 Row_number似乎是在第二个查询中使用滞后函数的方法,但我不能完全得到它100%。
以下是我的数据结构:
CREATE TABLE emailhell(
mainID INTEGER NOT NULL PRIMARY KEY
,acctID VARCHAR(4) NOT NULL
,emailID VARCHAR(2) NOT NULL
,type INTEGER NOT NULL
,created DATETIME NOT NULL
);
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (1,'1234','1',6,'1/1/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (2,'1234','1',11,'1/1/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (3,'1234','2',6,'1/2/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (4,'1234','3',6,'1/3/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (5,'1234','4',6,'1/4/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (6,'ABC','89',6,'1/5/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (7,'ABC','90',6,'1/6/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (8,'ABC','90',11,'1/7/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (9,'258','22',6,'1/7/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (10,'258','1',6,'1/10/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (11,'258','2',6,'1/30/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (12,'258','3',6,'1/31/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (13,'258','29',6,'2/15/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (14,'258','29',11,'2/16/2018');
INSERT INTO emailhell(mainID,acctID,emailID,type,created) VALUES (15,'258','31',6,'3/1/2018');
和我想要的输出
+--------+--------+---------+------+-----------+-------+------------+
| mainID | acctID | emailID | type | created | index | touchcount |
+--------+--------+---------+------+-----------+-------+------------+
| 1 | 1234 | 1 | 6 | 1/1/2018 | 1 | |
| 2 | 1234 | 1 | 11 | 1/1/2018 | 2 | 1 |
| 3 | 1234 | 2 | 6 | 1/2/2018 | 1 | |
| 4 | 1234 | 3 | 6 | 1/3/2018 | 2 | |
| 5 | 1234 | 4 | 6 | 1/4/2018 | 3 | |
| 6 | ABC | 89 | 6 | 1/5/2018 | 1 | |
| 7 | ABC | 90 | 6 | 1/6/2018 | 2 | |
| 8 | ABC | 90 | 11 | 1/7/2018 | 3 | 2 |
| 9 | 258 | 22 | 6 | 1/7/2018 | 1 | |
| 10 | 258 | 1 | 6 | 1/10/2018 | 2 | |
| 11 | 258 | 2 | 6 | 1/30/2018 | 3 | |
| 12 | 258 | 3 | 6 | 1/31/2018 | 4 | |
| 13 | 258 | 29 | 6 | 2/15/2018 | 5 | |
| 14 | 258 | 29 | 11 | 2/16/2018 | 6 | 5 |
| 15 | 258 | 31 | 6 | 3/1/2018 | 1 | |
+--------+--------+---------+------+-----------+-------+------------+
以下是我正在使用的内容但由于某种原因,当活动看起来有问题时,类型6后跟一个11后跟一个6,11等。这是我的查询开始,我确定有一个更好的方法来做到这一点。然后我使用LAG函数进行类似的查询以获取类型11出现的时间。
SELECT dm.TABLE.*,
row_number() over(partition by dm.acctId, dm.type order by dm.acctId, dm.created_date) as index into dm.table2
from dm.TABLE with (NOLOCK)