Note that there are some explanatory texts on larger screens.

plurals
  1. POSelf join with inner and outer join query
    primarykey
    data
    text
    <p>I have a table that is set up so that one column (attribute) contains information like first name, last name, account number and any other information related to a thing in the database. Another column (attributeType) contains a number indicating what the attribute is e.g. 1 might be first name, 2 last name and 3 account number etc. There is another column (enddate) indicating if the record is current by having a date there. Usually it will be set to the year 9999 when current and some date in the past otherwise. All data describing the same thing has a unique value too in another column (entity) so that each record with the same number in the entity column will be describing the one person. E.g.</p> <pre><code>entity attribute attributetype enddate ------ --------- ------------- -------- 1 ben 1 9999-1-1 1 alt 2 9999-1-1 1 12345 3 9999-1-1 2 sam 1 9999-1-1 2 smith 2 9999-1-1 2 98765 3 1981-1-1 </code></pre> <p>I want to select a person from the above table with a specific 1st and last name where the name will be current but not output the account number if it is not. Assuming the table is called tblAccount I do the following for the name part:</p> <pre><code>select ta1.attribute '1st Name', ta2.attribute 'last name' from tblAccount ta1 inner join tblAccount ta2 on ta1.entity = ta2.entity where ta1.attribute = 'sam' and ta2.attribute = 'smith' and ta1.attributetype = 1 and ta2. attributetype = 2 and ta1.enddate &gt; getdate() and ta2.enddate &gt; getdate() </code></pre> <p>and it outputs the first and last names as expected, but when I want to include the account number column I get nothing output:</p> <pre><code>select ta1.attribute '1st Name', ta2.attribute 'last name', ta3.attribute 'account#' from tblAccount ta1 inner join tblAccount ta2 on ta1.entity = ta2.entity left join tblAccount ta3 on ta1.entity = ta3.entity where ta1.attribute = 'sam' and ta2.attribute = 'smith' and ta1.attributetype = 1 and ta2. attributetype = 2 and ta1.enddate &gt; getdate() and ta2.enddate &gt; getdate() and ta3.attributetype = 3 and ta3.enddate &gt; getdate() </code></pre> <p>What I would like to see is the first and last names output with nothing in the account# column in the above case where it is not current. What am I doing wrong and how can I correct this query?</p>
    singulars
    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