I have a table AddressTypes with 4 records (home,office,vacation,hotel) and a table Address that share the filed addresstypeid.
In address table I have 1 record of type "home" and i want a query where I get 4 rows like this:
Type Address1 Address2 City State
home piping 1232 Austin Tx
office null null null null
vacation null null null null
hotel null null null null
Here is an image of tables: http://tinypic.com/view.php?pic=28078xv&s=6
Im sure is something very easy maybe using cross join but dont get it. Hope someone can guide me. Appreciate in advance.
Left joining AdddressTypes to Addresses will produce desired result:
select at.Type,
a.Address1,
a.Address2,
a.City,
a.State
from AddressTypes at
left join Address a
on at.AddressTypeID = a.AddressTypeID
-- For this query to make sense
-- Filter one person only
and a.PersonID = @PersonID
----------- THIS PART WAS ADDED BY VAAA ------------------------
Nikola, I change to this:
select at.description,
a.Address1,
a.Address2,
a.City
from address_types at
left join Address a
on 1 = 1
-- For this query to make sense
-- Filter one person only
and a.addressid = 24
And then I get the 4 rows, but all of them have the same address info and just the "home" type address is the one with data. So its close...
Use the LEFT OUTER JOIN, which returns one copy of matching records from both the left and right tables and non-matching records from both the tables. Here is the test code I tried:
CREATE TABLE AddressTypes(
AddressType SMALLINT NOT NULL,
[Description] NVARCHAR(50))
ALTER TABLE AddressTypes
ADD CONSTRAINT PK_AddressTypes_AddressType
PRIMARY KEY (AddressType)
CREATE TABLE [Address] (
AddressID INT NOT NULL,
AddressType SMALLINT,
Address1 NVARCHAR(50),
Address2 NVARCHAR(50),
City NVARCHAR(50),
State CHAR(2))
ALTER TABLE [Address]
ADD CONSTRAINT PK_Address_AddressID
PRIMARY KEY (AddressID)
ALTER TABLE [Address]
ADD CONSTRAINT FK_address_addresstypes_addresstype
FOREIGN KEY (AddressType) REFERENCES AddressTypes(AddressType)
INSERT INTO AddressTypes VALUES (1, 'home'), (2, 'office'),
(3, 'vacation'), (4, 'hotel')
INSERT INTO address VALUES (1, 1, 'piping', '1232', 'Austin', 'TX')
-- Here is the query that outputs the result set.
SELECT AT.AddressType AS [Type], A.Address1, A.Address2, A.City, A.State
FROM AddressTypes AT
LEFT OUTER JOIN address A
ON AT.AddressType = A.AddressType
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.