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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 tricky select

Author  Topic 

hollydonut
Starting Member

1 Post

Posted - 2012-06-11 : 02:49:20
hi i have question about union an join

currently i have 4 tables

table A
IdA descr
1 one
2 two
4 four


table B
idA idB amountB
1 XX 100
1 yy 200
4 yy 200


table C
idA idB idC amountC
1 xx aaa 50
1 xx bbb 25
4 yy ccc 200


table D
Nbr amount idA idB idC
001 50 1 xx bbb
002 45 1 yy ccc
003 46 3 ss ddd


and i need to make the result like

Nbr amount idA idB idC AmountB AmountC
001 50 1 xx bbb 100 50
002 45 1 yy ccc 200 ---
003 46 3 ss ddd --- ---
--- -- 4 yy ccc 200 200




sorry i cant make the table looks good.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-06-11 : 15:55:03
i'm hoping

001 50 1 xx bbb 100 50

was a typo
and it should be

001 50 1 xx bbb 100 25

if that being case, you can use below

SELECT m.*,b.amountB
FROM
(
SELECT d.Nbr,
d.amount,
COALESCE(d.idA,c.idA) AS idA,
COALESCE(d.idB,c.idB) AS idB,
COALESCE(d.idC,c.idC) AS idC,
c.amountC
FROM tableD d
FULL OUTER JOIN tableC c
ON c.idA = d.idA
AND c.idB = d.idB
AND c.idC = d.idC
)m
LEFT JOIN [tableB] b
ON b.idA = m.idA
AND b.idB = m.idB


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

vinu.vijayan
Posting Yak Master

227 Posts

Posted - 2012-06-12 : 08:19:36
Understanding The Logic behind your Expected output was very hard. I still don't know if I understand it completely. Is this what you are looking for:


Select x.Nbr, MAX(x.amount) As Amount, MAX(x.idA) As idA, MAX(x.idB) As idB, MAX(x.idC) As idC, MIN(x.amountB) As amountB, MIN(x.amountC) As amountC From
(Select D.Nbr, D.amount, Coalesce(D.idA, c.IdA) As idA, Coalesce(D.idB, c.IdB) As idB, Coalesce(D.idC, c.IdC) As idC, B.amountB, C.amountC From A
JOIN B ON A.IdA = B.idA
JOIN C ON A.IdA = C.idA
Full JOIN D ON A.IdA = D.idA) As x
Group By x.Nbr


N 28° 33' 11.93148"
E 77° 14' 33.66384"
Go to Top of Page
   

- Advertisement -