我有一個crashes大約有 100 萬行的表,每行包含以下任一方面的資料:
每一次不是在學校附近發生的車禍,或
發生在學校附近的每一次車禍,如果發生在不止一所學校附近,則每次事故都會增加行(例如,4 所學校附近發生的事故為 4 行)。一次事故的最高行數/附近學校是 10。
我想向表中添加一列,對于出現在多行中的每個 crash_id 僅出現一次回傳“1”,并為列中隨后出現的相同 crash_id 回傳“0” crash_id。每個 crash_id 哪一行有 1 或 0 并不重要。
我已經嘗試了針對這個類似問題提供的所有建議,但我無法讓其中任何一個對我有用。
FWIW,我使用這個公式讓它在Excel中作業:
=(COUNTIF($C$2:$C2,$C2)=1) 0
但那是針對一張小表,而不是一百萬行的表。
到目前為止我嘗試過的:
SELECT *
FROM
(
SELECT * , ROW_NUMBER() OVER(PARTITION BY crash_id) AS row
FROM crashes
) AS A1
WHERE row <6
SELECT *
FROM
(
SELECT * , ROW_NUMBER() OVER(PARTITION BY crash_id) AS row
FROM crashes
) AS A1
WHERE row = 1
我知道這不是最佳的資料庫設計,但它允許我獲得大部分我需要的東西,除了我上面描述的東西。
uj5u.com熱心網友回復:
只是一個簡單的測驗,將 first_crash 列添加到崩潰中。
但是它需要一些東西來確定哪一行是第一行。由于表本質上是未排序的集合。
該示例為此使用了 ID。
create table crashes ( id serial primary key, crash_id int, school_id int ); alter table crashes add constraint uniq_school_crash unique (crash_id, school_id); insert into crashes (crash_id, school_id) values (101,11), (101,10), (101,12) , (102,25), (102,24), (102,23) , (103,null) alter table crashes add column first_crash int default 0;
update crashes c set first_crash = 1 where first_crash = 0 and ( school_id is null or not exists ( select 1 from crashes c2 where c2.crash_id = c.crash_id and c2.id < c.id ));
select * from crashes order by id身份證 | crash_id | school_id | 第一次崩潰 -: | -------: | --------: | ----------: 1 | 101 | 11 | 1 2 | 101 | 10 | 0 3 | 101 | 12 | 0 4 | 102 | 25 | 1 5 | 102 | 24 | 0 6 | 102 | 23 | 0 7 | 103 | 空| 1
db<>在這里擺弄
額外的
- 按 row_number 更新
-- using row_number
update crashes c
set first_crash = q.rn
from (
select id
, row_number() over (partition by crash_id
order by id asc) as rn
from crashes
) q
where q.rn = 1
and q.id = c.id;
- 使用臨時表
-- using temporary table
create temporary table tmp_crashes (
id int primary key,
crash_id int
);
insert into tmp_crashes (id, crash_id)
select min(id), crash_id
from crashes
group by crash_id
order by min(id);
update crashes t
set first_crash = 1
from tmp_crashes tmp
where tmp.id = t.id;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/383303.html
標籤:sql PostgreSQL的
