我有一张按时间和地点分类的动物位置表。当位置从一个id变为下一个id时,我想增加一个计数器。所以动物的每个“停留”都应该得到一个唯一的id(计数器)。我有一个非sql描述:
counter = 0
CASE (location at ID = location at ID-1) SET counter+1
我尝试使用dense_rank(),但未能正确设置分区。这是一个带有所需计数器的样品。
ID Location Counter
1 3 1
2 3 1
3 2 2
4 2 2
5 3 3
6 1 4
7 3 5
8 3 5
9 3 5
CREATE TABLE locations (idn serial PRIMARY KEY, location integer);
INSERT INTO locations (location ) VALUES (3);
INSERT INTO locations (location ) VALUES (3);
INSERT INTO locations (location ) VALUES (2);
INSERT INTO locations (location ) VALUES (2);
INSERT INTO locations (location ) VALUES (3);
INSERT INTO locations (location ) VALUES (1);
INSERT INTO locations (location ) VALUES (3);
INSERT INTO locations (location ) VALUES (3);
INSERT INTO locations (location ) VALUES (3);
1条答案
按热度按时间nfeuvbwi1#
你可以试试lag函数。
下面是一个适用于大型sql的示例:
输出: