简体   繁体   English

SQL查询获取两张表中一列唯一值的所有记录

[英]SQL query to get all records with a unique value of one column from two tables

I am using SQL Server 2012 and Access.我正在使用 SQL Server 2012 和 Access。

I have two tables indexed on Well and Depth.我有两张在 Well 和 Depth 上索引的表。 The depths in each table for each well can be the same or different.每个孔的每个表中的深度可以相同或不同。 I wish to create a single table with Well, Depth (one column each) and all other columns of the two tables, containing a list of all unique depths and the associated data at each depth.我希望创建一个包含Well, Depth (每列一列)和两个表的所有其他列的单个表,其中包含所有唯一深度的列表以及每个深度的相关数据。

The tables shown here are an example:此处显示的表格是一个示例:

Table PT表 PT

Well出色地 Depth深度 Temperature温度
A1 A1 100 100 10 10
A1 A1 150 150 15 15
A1 A1 200 200 20 20
A1 A1 250 250 25 25
A1 A1 300 300 30 30
A2 A2 69 69 121 121

Table SPIN表旋转

Well出色地 Depth深度 Frequency频率
A1 A1 100 100 1000 1000
A1 A1 120 120 1200 1200
A1 A1 200 200 2000 2000
A1 A1 300 300 3000 3000
A1 A1 500 500 5000 5000
B2 B2 103 103 250 250

The combined table, SPINPT, for well A1 should look like this: A1 井的组合表 SPINPT 应如下所示:

Well出色地 Depth深度 Temperature温度 Frequency频率
A1 A1 100 100 10 10 1000 1000
A1 A1 120 120 1200 1200
A1 A1 150 150 15 15
A1 A1 200 200 20 20 2000 2000
A1 A1 250 250 25 25
A1 A1 300 300 30 30 3000 3000
A1 A1 500 500 5000 5000

I hoped this would be fairly easy, but I have searched the internet for solutions without success.我希望这会相当容易,但我在互联网上搜索了解决方案,但没有成功。

You seem to want a full outer join between the two tables:您似乎想要两个表之间的完全外连接:

SELECT
    COALESCE(p.Well, s.Well) AS Well,
    COALESCE(p.Depth, s.Depth) AS Depth,
    p.Temperature,
    s.Frequency
FROM PT p
FULL OUTER JOIN SPIN s
    ON s.Well = p.Well AND
       s.Depth = p.Depth
ORDER BY
    Well,
    Depth;

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM