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 query

Author  Topic 

sql76
Starting Member

2 Posts

Posted - 2009-09-26 : 06:23:45
Hello,
I found this forum while searching in Google about SQL.
I'm new to database programming and I don't know how to solve my problem and even how to define my question, that's why I made an example. Let's have a database with 2 tables:

+---------------------+
| table1 |
+---+--------+--------+
|aid|counter1|counter2|
+---+--------+--------+
| 1 | 5 | 2 |
+---+--------+--------+
| 2 | 7 | 3 |
+---+--------+--------+
| 3 | 8 | 4 |
+---+--------+--------+
| 4 | 10 | 8 |
+---+--------+--------+
| 5 | 12 | 11 |
+---+--------+--------+
| 6 | 18 | 15 |
+---+--------+--------+

and

+---------------------+
| table2 |
+---+--------+--------+
|bid|counter1|counter2|
+---+--------+--------+
| 1 | 2 | 1 |
+---+--------+--------+
| 2 | 7 | 2 |
+---+--------+--------+
| 3 | 8 | 5 |
+---+--------+--------+
| 4 | 11 | 7 |
+---+--------+--------+
| 5 | 13 | 10 |
+---+--------+--------+
| 6 | 18 | 12 |
+---+--------+--------+


I need a query that returns the following result when counter1 = 7 and counter2 sorted in ascending order:

+---+---+--------+
|aid|bid|counter2|
+---+---+--------+
|nul| 2 | 2 |
+---+---+--------+
|2 |nul| 3 |
+---+---+--------+

Is it possible such query to be made?

weipublic
Starting Member

19 Posts

Posted - 2009-09-27 : 23:05:20
select * from
(
select aid, bid = null, counter2 from Table1 where counter1=7
union all
select aid= null, bid , counter2 from Table2 where counter1=7
) v
order by v.counter2
Go to Top of Page

sql76
Starting Member

2 Posts

Posted - 2009-09-28 : 03:38:18
weipublic, thank you very much!
It works
Go to Top of Page
   

- Advertisement -