Thursday, March 29, 2012

Alternate rows from different table

Dear All,
I have a requirement in which I have to display a row from one
table & the corresponding row from the another table. e.g. say there
are 2 tables T1 & T2. Suppose there is a record in T1 say R1 & the
corresponding record in T2 as R1' then the display would come as
R1 /* Data from Table 1 */
R1' /* Data from Table 2 */
R2
R2'
& so on.....
This is possible by manipulating the resultset in a program. But I
would like to know if it is possible in the SQL query.
Thanks & Regards,
Praveenpkb wrote:

> Dear All,
> I have a requirement in which I have to display a row from one
> table & the corresponding row from the another table. e.g. say there
> are 2 tables T1 & T2. Suppose there is a record in T1 say R1 & the
> corresponding record in T2 as R1' then the display would come as
> R1 /* Data from Table 1 */
> R1' /* Data from Table 2 */
> R2
> R2'
> & so on.....
> This is possible by manipulating the resultset in a program. But I
> would like to know if it is possible in the SQL query.
> Thanks & Regards,
> Praveen
Looks like a UNION to me. Assuming r is the common column that
determines R1, R2, etc, try:
SELECT r, col1, col2, ...
FROM
(SELECT r, 1 AS tbl, col1, col2, ...
FROM tbl1
UNION ALL
SELECT r, 2 AS tbl, col1, col2, ...
FROM tbl2) AS T
ORDER BY r, tbl ;
If that's not what you wanted then my signature explains how to post
better questions so that you can get better answers. :-)
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||"pkb" <praveen.bhushan@.gmail.com> wrote in message
news:1138803314.265069.114980@.g49g2000cwa.googlegroups.com...
> Dear All,
> I have a requirement in which I have to display a row from one
> table & the corresponding row from the another table. e.g. say there
> are 2 tables T1 & T2. Suppose there is a record in T1 say R1 & the
> corresponding record in T2 as R1' then the display would come as
> R1 /* Data from Table 1 */
> R1' /* Data from Table 2 */
> R2
> R2'
> & so on.....
> This is possible by manipulating the resultset in a program. But I
> would like to know if it is possible in the SQL query.
> Thanks & Regards,
> Praveen
You could:
select 1 AS rank, ... from T1 where ...
union
select 2 AS rank, ... from T2 where ...
Order by (you will have to add the corresponding columns, whatever that is),
rank
Sorry, can't give you anything more detailed without your table structure.|||Hi David, Raymond,
Thanks for your quick replies. The only problem in the above
solution will come when there is a record which is present in
one of the tables. Actually I wanted to make pairs from the two tables.
Well I have got the idea.
Regards,
Praveen

No comments:

Post a Comment