简体   繁体   English

在两个表上使用 INNER JOIN 时,如何让它返回表中的每一列,

[英]How do I get it to return every column in a table when using INNER JOIN on two tables,

Table dbo.Ögon表 dbo.Ögon

Table dbo.CaseTable表 dbo.CaseTable

I have imported a.csv file and created a table out of the.csv file.我导入了 .csv 文件并从 .csv 文件中创建了一个表。 It contains two columns that matches columns/values of a another table.它包含与另一个表的列/值匹配的两列。 This.csv file contains 2245 rows which also is the amount of rows in table I created called dbo.Ögon This.csv 文件包含 2245 行,这也是我创建的名为dbo.Ögon的表中的行数

Down below is the INNER JOIN query I've written.下面是我编写的INNER JOIN查询。

SELECT * FROM [dbo].[CaseTable] P
INNER JOIN [dbo].[Ögon] O
ON P.Personnummer = O.Pnr;

This returns a result of 9085 rows which's not the result i was lookin for.这将返回 9085 行的结果,这不是我要查找的结果。

But!但!

If I write the query this way instead.如果我改用这种方式编写查询。

SELECT DISTINCT Personnummer, Fotodatum
FROM [dbo].[CaseTable] P
INNER JOIN [dbo].[Ögon] O
ON P.Personnummer = O.Pnr;

I get the exact same rows as the.csv file or as in table dbo.Ögon but I also see two columns.我得到与 .csv 文件或表dbo.Ögon中完全相同的行,但我也看到两列。

So.所以。 What i'm looking for as a result when running query, is to see every column instead of two columns with the amount of rows that I stated before.结果,我在运行查询时要寻找的是查看每一列而不是两列,其中包含我之前声明的行数。

To clarify.澄清。 Im looking for a column called CaseKey which does not exist in table dbo.Ögon but exists in table dbo.CaseTable我正在寻找一个名为 CaseKey 的列,它在表dbo.Ögon中不存在但存在于表dbo.CaseTable

Hence why im looking for a query that returns all columns so I can see column CaseKey.因此,为什么我要寻找一个返回所有列的查询,以便我可以看到 CaseKey 列。

Hope I didn't make this too confusing:)希望我没有让这太混乱:)

You appear to have duplicates -- I am guessing in the ogon table.您似乎有重复项——我猜是在ogon表中。 One method uses ROW_NUMBER() .一种方法使用ROW_NUMBER() If this interpretation is correct, you can use:如果这个解释是正确的,你可以使用:

SELECT p.*, o.*
FROM [dbo].[CaseTable] p JOIN
     (SELECT o.*, 
             ROW_NUMBER() OVER (PARTITION BY o.Pnr, o.FotoDatum ORDER BY NEWID()) as seqnum
      FROM [dbo].[Ögon] o
     ) o
     ON p.Personnummer = o.Pnr AND seqnum = 1;

Note that you would normally have an ORDER BY in the ROW_NUMBER() to specify which row you want.请注意,您通常会在ROW_NUMBER()中有一个ORDER BY来指定您想要行。

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

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