Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Help with SQL Join statement

Author  Topic 

boybles
Starting Member

23 Posts

Posted - 2007-07-22 : 13:52:09
I have 3 tables, a Store_Tbl for stores,
a Store_Mall_Tbl to associate stores in malls
and a Store_ATM_tbl to associate ATM types in
stores.

Store_Tbl
--------------
StoreID|StoreName
-----------------
1|GAP
2|Banana Republic
3|Broadway
4|May Company
5|Sears



Store_Mall_Tbl
--------------------
StoreID|MallID
-----------------
1|1
2|1
3|1
4|1
5|1


Store_ATM_Tbl
------------------
StoreID|ATMID
------------------
1|1
2|1
3|1



How can I run a query w/ appropriate outer joins to fetch
StoreName and ATM availability given an ATMID and a MallID

Ex:
Input: ATMID=1, MallID=1

Output:

StoreName|ATM
---------------
GAP|YES
Banana Republic|YES
Broadway|YES
MayCompany|NO
Sears|NO

Please Help!

Boybles

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-07-22 : 14:10:15
[code]-- Prepare sample data
DECLARE @Store TABLE (StoreID INT, StoreName VARCHAR(20))

INSERT @Store
SELECT 1, 'GAP' UNION ALL
SELECT 2, 'Banana Republic' UNION ALL
SELECT 3, 'Broadway' UNION ALL
SELECT 4, 'May Company' UNION ALL
SELECT 5, 'Sears'

DECLARE @Mall TABLE(StoreID INT, MallID INT)

INSERT @Mall
SELECT 1, 1 UNION ALL
SELECT 2, 1 UNION ALL
SELECT 3, 1 UNION ALL
SELECT 4, 1 UNION ALL
SELECT 5, 1

DECLARE @ATM TABLE (StoreID INT, ATMID INT)

INSERT @ATM
SELECT 1, 1 UNION ALL
SELECT 2, 1 UNION ALL
SELECT 3, 1

-- Do the work
DECLARE @ATMID INT,
@MallID INT

SELECT @ATMID = 1,
@MallID = 1

SELECT s.StoreName,
CASE
WHEN a.StoreID IS NULL THEN 'No'
ELSE 'Yes'
END AS ATM
FROM @Store AS s
INNER JOIN @Mall AS m ON m.StoreID = s.StoreID
LEFT JOIN @ATM AS a ON a.StoreID = s.StoreID
AND a.ATMID = @ATMID
WHERE m.MallID = @MallID[/code]

Peter Larsson
Helsingborg, Sweden
Go to Top of Page

boybles
Starting Member

23 Posts

Posted - 2007-07-23 : 21:10:57
Beautiful!!! Thank you so much, Peter!
Go to Top of Page
   

- Advertisement -