2017-10-11 68 views
0

我已將一列(seq)添加到用於調度的表中,因此前端可以管理每個項目可以顯示的順序。是否可以創建一個SQL查詢,以基於日期列中常見重複值的增量計數器填充此列?Postgresql - 在列中有重複值的行中增加計數器

之前

------------------------------------ 
| name | date_time   | seq | 
------------------------------------ 
| ABC1 | 15-01-2017 11:00:00 |  | 
| ABC2 | 16-01-2017 11:30:00 |  | 
| ABC1 | 16-01-2017 11:30:00 |  | 
| ABC3 | 17-01-2017 10:00:00 |  | 
| ABC3 | 18-01-2017 12:30:00 |  | 
| ABC4 | 18-01-2017 12:30:00 |  | 
| ABC1 | 18-01-2017 12:30:00 |  | 
------------------------------------ 

------------------------------------ 
| name | date_time   | seq | 
------------------------------------ 
| ABC1 | 15-01-2017 11:00:00 | 0 | 
| ABC2 | 16-01-2017 11:30:00 | 0 | 
| ABC1 | 16-01-2017 11:30:00 | 1 | 
| ABC3 | 17-01-2017 10:00:00 | 0 | 
| ABC3 | 18-01-2017 12:30:00 | 0 | 
| ABC4 | 18-01-2017 12:30:00 | 1 | 
| ABC1 | 18-01-2017 12:30:00 | 2 | 
------------------------------------ 

解決了,感謝兩個答案。 爲了使它更容易爲任何人誰發現這一點,工作代碼爲:

UPDATE my_table f 
    SET seq = seq2 
    FROM (
     SELECT ctid, ROW_NUMBER() OVER (PARTITION BY date_time ORDER BY ctid) -1 AS seq2 
     FROM my_table 
     ) s 
    WHERE f.ctid = s.ctid; 

回答

1

使用window functionrow_number()

with my_table (name, date_time) as (
values 

('ABC1', '15-01-2017 11:00:00'), 
('ABC2', '16-01-2017 11:30:00'), 
('ABC1', '16-01-2017 11:30:00'), 
('ABC3', '17-01-2017 10:00:00'), 
('ABC3', '18-01-2017 12:30:00'), 
('ABC4', '18-01-2017 12:30:00'), 
('ABC1', '18-01-2017 12:30:00') 
) 

select *, 
    row_number() over (partition by name order by date_time)- 1 as seq 
from my_table 
order by date_time; 

name |  date_time  | seq 
------+---------------------+----- 
ABC1 | 15-01-2017 11:00:00 | 0 
ABC1 | 16-01-2017 11:30:00 | 1 
ABC2 | 16-01-2017 11:30:00 | 0 
ABC3 | 17-01-2017 10:00:00 | 0 
ABC1 | 18-01-2017 12:30:00 | 2 
ABC3 | 18-01-2017 12:30:00 | 1 
ABC4 | 18-01-2017 12:30:00 | 0 
(7 rows) 

對類似的問題有關更新現有記錄有唯一的整數讀this answer

+0

這提供了數字,我怎麼用這些數字更新表格? – corky

2

退房ROW_NUMBER()

SELECT name, date_time, ROW_NUMBER() OVER (PARTITION BY date_time ORDER BY name) FROM [table] 
+0

顯示的數字非常好,但不會填充新列。 – corky

+0

這將返回以下錯誤: 錯誤:關係「t」不存在 LINE 1:UPDATE t set seq = seq2 FROM( – corky

+0

原來我的UPDATE語句在PostGres中不起作用(但它在SQL Server中起作用)。你的表需要一個主鍵來更新,或者你可以做一些事情,如https://stackoverflow.com/a/6578705/1933308 – zambonee