SQL 连接两个视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8198760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:20:25  来源:igfitidea点击:

SQL to join two views

sqldatabasejoinviews

提问by hampusohlsson

Need some help joining these two tables

需要一些帮助来连接这两个表

I have two views that looks like this

我有两个看起来像这样的视图

view1                view2
+------+--------+    +------+--------+
| code | SUM(*) |    | code | SUM(*) |
+------+--------+    +------+--------+
| AAA  |      4 |    | AAA  |      4 |
| BBB  |      3 |    | CCC  |      1 |
+------+--------+    +------+--------+

I want to join them into a table that looks like this

我想将它们加入一个看起来像这样的表中

+------+--------+
| code | SUM(*) |
+------+--------+
| AAA  |      4 |
| BBB  |      3 |
| CCC  |      1 |    
+------+--------+ 

I have tried, but only failed..

我试过了,但只是失败了..

回答by

select *
from view1
union
select *
from view2

Utilizing a UNIONwill not return duplicate entries, which is what it seems you are looking for.

使用 aUNION不会返回重复的条目,这似乎是您正在寻找的。

回答by halfdan

You can use a UNIONfor this:

您可以UNION为此使用 a :

SELECT * FROM view1
UNION DISTINCT
SELECT * FROM view2

回答by Adam Robinson

For your first result, the answers posted using unionwill do the trick:

对于您的第一个结果,使用发布的答案可以解决问题union

select * from view1
union
select * from view2

However, given the fact that one of your columns is a sum, this seems unlikely to be what you actually want.

但是,鉴于您的一列是总和这一事实,这似乎不太可能是您真正想要的。

For your second result (where the values are added), you'll need to use a unionand a subquery:

对于您的第二个结果(添加值的地方),您需要使用 aunion和一个子查询:

select
    code,
    sum(yourcol)

from
(
    select
        code,
        yourcol

    from view1

    union all

    select
        code,
        yourcol

    from view2
) source

group by code