Note that there are some explanatory texts on larger screens.

plurals
  1. POSelect based on matching columns
    primarykey
    data
    text
    <p>I have two tables both containing various companies. I want to select everything from <code>tableOne</code> that appears in <code>tableTwo</code> (in fact, only if it appears in <code>tableTwo</code>). I’ll do this by comparing their <code>companyID</code> fields. They must also have the same value for a column <code>someYear</code>. So in other words, I want to return the companies that appear in <code>tableTwo</code> from <code>tableOne</code>, if and only if their <code>someYear</code> columns match.</p> <pre><code>tableOne companyID someYear --------- -------- 1 2010 2 2009 3 2011 1 2011 7 2009 tableTwo companyID someYear --------- -------- 1 2010 2 2008 3 2011 4 2011 5 2009 </code></pre> <p>I want to return <code>1</code> and <code>3</code> (company <code>2</code>’s year differs so I don’t want it). My useless attempt:</p> <pre><code>SELECT one.* FROM tableOne one, tableTwo two WHERE one.[companyID] in ( SELECT DISTINCT companyID FROM tableTwo ) and one.someYear = two.someYear; </code></pre> <p>The problem here is that it returns millions of rows, when both tables contain less than 10,000 entries. I can't recreate the output exactly because of sensitive information. The table/column names here are all made up as I'm sure you can tell. Also I should probably point out that <strong>neither table appears to have a primary key</strong>. I assume that causes them to have nothing to match on. I’m using SQL Server 2008. Any help would be hugely appreciated. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload