简体   繁体   中英

SQL Server : Join two rows. All columns from the 1st and 1 column from the second using an alias

This marks the first time I ask a question on stack overflow, and probably the 5000th time i've visited the site. So first off, thanks for all your hard work!

So I have a basic select query on a single table that returns two rows of similar data and are linked via a shared PK.

I want to retrieve all fields from the first row, and only one of the columns from the second under an alias.

Basically flattening the two records into one but only using one of the columns from the second row.

OK Here is a screenshot.

http://www.flickr.com/photos/imagevault/8581053528/

Looking at the first results window I want the Second "Comp" value to show up as an additional column on the first row as a "RentalComp". IF there is only one row returned for a given propertyid then it can just be null.

Thanks!

.. I'm at a loss of what to google for so here i am.

SELECT a.*, b.Comp AS RentalComp
FROM dbo.vwComps AS a LEFT OUTER JOIN dbo.vwComps AS b ON a.PropertyID = b.PropertyID 
AND b.ConfigurationUsed = 2
WHERE (a.ConfigurationUsed = 1)

The key was specifying multiple conditions in the 'ON' statement. THen doing a basic filter in the where clause.

I kept trying to do everything in the where an it was filtering everything out.

Is this what you're looking for?

SELECT t1.*, 
       t2.col
FROM   table1 t1
       JOIN table2 t2
       ON t1.key = t2.key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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