使用子查询更新 postgresql 中的列
Update column in postgresql using subquery
我在 postgresql 数据库中有一个 table 名称“table1”:
CREATE TABLE table1(
id TEXT,
class INT,
r1 DATE,
r2 DATE
);
INSERT INTO public.table1 (id, class, r1, r2)
VALUES ('x2', 2, '1/25/2015', '1/25/2015');
INSERT INTO public.table1 (id, class, r1, r2)
VALUES ('x2', 3, '6/28/2015', '1/25/2015');
INSERT INTO public.table1 (id, class, r1, r2)
VALUES ('x2', 3, '6/18/2015', '1/25/2015');
INSERT INTO public.table1 (id, class, r1, r2)
VALUES ('x5', 2, '9/3/2015', '1/25/2015');
INSERT INTO public.table1 (id, class, r1, r2)
VALUES ('x3', 1, '9/3/2015', '1/25/2015');
INSERT INTO public.table1 (id, class, r1, r2)
VALUES ('x3', 1, '8/3/2015', '1/25/2015');
我想做的是更新列 R2,这样对于每组 id 和 class,R2 将是该组 R1 的最小值:
expected_output:
我正在尝试做类似的事情,但没有给我正确的结果:
UPDATE table1
SET r2 = subquery.p FROM (select id, class, r1, min(r1) OVER (partition by class, id) AS p
FROM table1) AS subquery
有人可以帮我查询一下吗?
谢谢
这可能最容易使用更新并加入最小值的 CTE 来完成:
WITH CTE AS (
select id, class, min(r1) OVER (partition by class, id) AS p
FROM table1
)
UPDATE table1 t1
SET r2 = CTE.p
FROM CTE
WHERE CTE.id = t1.id AND CTE.class = t1.class
Post 使用您的示例数据进行更新:
id class r1 r2
x2 2 01/25/2015 01/25/2015
x2 3 06/28/2015 06/18/2015
x2 3 06/18/2015 06/18/2015
x3 1 09/03/2015 08/03/2015
x3 1 08/03/2015 08/03/2015
x5 2 09/03/2015 09/03/2015
我在 postgresql 数据库中有一个 table 名称“table1”:
CREATE TABLE table1(
id TEXT,
class INT,
r1 DATE,
r2 DATE
);
INSERT INTO public.table1 (id, class, r1, r2)
VALUES ('x2', 2, '1/25/2015', '1/25/2015');
INSERT INTO public.table1 (id, class, r1, r2)
VALUES ('x2', 3, '6/28/2015', '1/25/2015');
INSERT INTO public.table1 (id, class, r1, r2)
VALUES ('x2', 3, '6/18/2015', '1/25/2015');
INSERT INTO public.table1 (id, class, r1, r2)
VALUES ('x5', 2, '9/3/2015', '1/25/2015');
INSERT INTO public.table1 (id, class, r1, r2)
VALUES ('x3', 1, '9/3/2015', '1/25/2015');
INSERT INTO public.table1 (id, class, r1, r2)
VALUES ('x3', 1, '8/3/2015', '1/25/2015');
我想做的是更新列 R2,这样对于每组 id 和 class,R2 将是该组 R1 的最小值:
expected_output:
我正在尝试做类似的事情,但没有给我正确的结果:
UPDATE table1
SET r2 = subquery.p FROM (select id, class, r1, min(r1) OVER (partition by class, id) AS p
FROM table1) AS subquery
有人可以帮我查询一下吗?
谢谢
这可能最容易使用更新并加入最小值的 CTE 来完成:
WITH CTE AS (
select id, class, min(r1) OVER (partition by class, id) AS p
FROM table1
)
UPDATE table1 t1
SET r2 = CTE.p
FROM CTE
WHERE CTE.id = t1.id AND CTE.class = t1.class
Post 使用您的示例数据进行更新:
id class r1 r2
x2 2 01/25/2015 01/25/2015
x2 3 06/28/2015 06/18/2015
x2 3 06/18/2015 06/18/2015
x3 1 09/03/2015 08/03/2015
x3 1 08/03/2015 08/03/2015
x5 2 09/03/2015 09/03/2015