Selecting one record to many records

Please support our MS SQL advertiser: Intel Parallel Studio Home
Reply

Join Date: Apr 2006
Posts: 1
Reputation: PoisonElves is an unknown quantity at this point 
Solved Threads: 0
PoisonElves PoisonElves is offline Offline
Newbie Poster

Selecting one record to many records

 
0
  #1
Apr 23rd, 2006
Hi

I have 3 tables that I need to display in a report

TableA
idxA valueA
1, a
2, b
3, c

TableB
idxB bidxA valueB
1, 1, aa
2, 1, bb
3, 1, cc
4, 2, aa
5, 2, cc

TableC
idxC bidcA valueC
1, 1, dd
2, 1, ee
3, 2, ff
4, 2, gg
5, 2, hh
6, 2, ii

The resut I would like to display is
1 aa dd
1 bb ee
1 cc __
2 aa ff
2 cc gg
2 __ hh
2 __ ii

Does anyone have and idea and preferably an example on how to do something like this in SQL

Thanks
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 483
Reputation: campkev is an unknown quantity at this point 
Solved Threads: 19
campkev campkev is offline Offline
Posting Pro in Training

Re: Selecting one record to many records

 
0
  #2
Apr 24th, 2006
not possible (or at least extremely difficult to do and to maintain) the way you have the database setup as there is no way (other than the order that they are entered in the database, which is rather unreliable) to tell how tables b and c are linked. However if you change your setup and have tableC look like this

idxC , bidcA ,bidcb ,valueC

then you can run your query like this:
  1. SELECT idxA, valueb, valuec FROM tablea, tableb, tablec
  2. WHERE (idxa = bidxa AND idxa = bidca AND bidcb=idxb)
  3. union
  4. SELECT idxA, NULL AS valueb, valuec FROM tablea, tablec
  5. WHERE idxa = bidca AND bidcb IS NULL
  6. union
  7. SELECT idxA, valueb,NULL AS valuec FROM tablea, tableb
  8. WHERE idxa = bidxa AND idxb NOT IN (SELECT bidcb FROM tablec WHERE bidcb IS NOT NULL)
  9.  
  10. ORDER BY idxA ASC,valueb ASC, valuec ASC
which will give you a result that looks like
  1. idxA valueb valuec
  2. 1 aa dd
  3. 1 bb ee
  4. 1 cc
  5. 2 hh
  6. 2 ii
  7. 2 aa ff
  8. 2 cc gg

slightly different order, but that is unavoidable as nulls come first when sorting alphabetically
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC