我想把这两个表结合起来。
我想插入新行,如果它们与行
中的值匹配,则更新列数中的值表1是目标,表2是来源。
表1
c1 c2 c3 c4 c5 number
1 2 3 4 5 3
2 3 4 5 6 2
2 3 5 6 7 2
表2
c1 c2 c3 c4 c5 number
1 3 4 5 6 3
1 2 3 4 5 2
select查询是否可以采用以下格式返回数据顺序
结果(表1)
c1 c2 c3 c4 c5 number
1 2 3 4 5 5
1 3 4 5 6 3
2 3 4 5 6 2
2 3 5 6 7 2
答案 0 :(得分:1)
如果您不介意从Table1删除数据然后插入新数据,您可以这样做:
with cte1 as (
delete from Table1
returning *
), cte2 as (
select c1, c2, c3, c4, c5, cnt from cte1
union all
select c1, c2, c3, c4, c5, cnt from Table2
)
insert into Table1
select c1, c2, c3, c4, c5, sum(cnt)
from cte2
group by c1, c2, c3, c4, c5;
<强> sql fiddle demo 强>
如果您真的想更新/插入数据,可以这样做:
with cte_upsert as (
update Table1 as T1 set
cnt = T1.cnt + T2.cnt
from Table2 as T2
where
T1.c1 = T2.c1 and T1.c2 = T2.c2 and
T1.c3 = T2.c3 and T1.c4 = T2.c4 and
T1.c5 = T2.c5
returning T1.*
)
insert into Table1
select T2.c1, T2.c2, T2.c3, T2.c4, T2.c5, T2.cnt
from Table2 as T2
where
not exists (
select *
from cte_upsert as T1
where
T1.c1 = T2.c1 and T1.c2 = T2.c2 and
T1.c3 = T2.c3 and T1.c4 = T2.c4 and
T1.c5 = T2.c5
);
<强> sql fiddle demo 强>
或者你可以做最明显的一个:
update Table1 as T1 set
cnt = T1.cnt + T2.cnt
from Table2 as T2
where
T1.c1 = T2.c1 and T1.c2 = T2.c2 and
T1.c3 = T2.c3 and T1.c4 = T2.c4 and
T1.c5 = T2.c5;
insert into Table1
select T2.c1, T2.c2, T2.c3, T2.c4, T2.c5, T2.cnt
from Table2 as T2
where
not exists (
select *
from Table1 as T1
where
T1.c1 = T2.c1 and T1.c2 = T2.c2 and
T1.c3 = T2.c3 and T1.c4 = T2.c4 and
T1.c5 = T2.c5
);
<强> sql fiddle demo 强>
答案 1 :(得分:0)
我知道它不是优化解决方案,但它会解决您的问题
select
a.c1 as c1 , a.c2 as c2, a.c3 as c3, a.c4 as c4, a.c5 as c5, a.count + b.count as count
from
t1 a
join
t2 b ON (a.c1 = b.c1 and a.c2 = b.c2
and a.c3 = b.c3
and a.c4 = b.c4
and a.c5 = b.c5)
union all
(select
a.c1 as c1 , a.c2 as c2, a.c3 as c3, a.c4 as c4, a.c5 as c5, a.count as count
from
t1 a
LEFT join
t2 b ON (a.c1 = b.c1 and a.c2 = b.c2
and a.c3 = b.c3
and a.c4 = b.c4
and a.c5 = b.c5)
WHERE b.c1 is null)
UNION all
select
a.c1 as c1 , a.c2 as c2, a.c3 as c3, a.c4 as c4, a.c5 as c5, a.count as count
from
t2 a
LEFT join
t1 b ON (a.c1 = b.c1 and a.c2 = b.c2
and a.c3 = b.c3
and a.c4 = b.c4
and a.c5 = b.c5)
WHERE b.c1 is null
答案 2 :(得分:0)
目前尚不清楚“count”是否是前一个查询或简单字段的聚合函数,但是,如果它是一个简单字段,如下面的数据:
CREATE TABLE table1(
c1 integer,
c2 integer,
c3 integer,
c4 integer,
c5 integer,
count integer
);
INSERT INTO table1 VALUES (1,2,3,4,5,3);
INSERT INTO table1 VALUES (2,3,4,5,6,2);
INSERT INTO table1 VALUES (2,3,5,6,7,2);
CREATE TABLE table2(
c1 integer,
c2 integer,
c3 integer,
c4 integer,
c5 integer,
count integer
);
INSERT INTO table2 VALUES (1,3,4,5,6,3);
INSERT INTO table2 VALUES (1,2,3,4,5,2);
您可以通过以下方式获取数据:
SELECT c1, c1,c2, c3, c4,c5,SUM(count) AS count
FROM (
SELECT * FROM table1
UNION ALL
SELECT * FROM table2) AS foo
GROUP BY c1, c2, c3, c4, c5
ORDER BY c1, c2, c3, c4, c5
我希望这可以帮到你