473,511 Members | 14,799 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SQL Query: Merging Tables

Jim
This SQL query has been driving me nuts, I am sure there is a simple
way of doing this but I am afraid it is eluding me at the moment.

I have two tables:

Table1
X Y
----------- -----------
1 12
2 41
6 14
9 12

Table2
X Y
----------- -----------
1 10
2 12
3 12
5 12
6 32

What I am after is a list of the maximum Y values for each value of X
from the tables:

X Y
----------- -----------
1 12
2 41
3 12
5 12
6 32
9 12

Any help would be greatly appreciated

Thanks - Jim

Jul 23 '05 #1
5 1519
Please always include DDL with future posts otherwise we are forced to
guess what keys, constraints, nullability, etc are supposed to apply to
the problem. If we have to guess then you might not get the right
answer or the best answer. You should also find you get good answers
quicker if you include sample data as INSERT statements rather than as
lists - that way others can test out possible solutions with your
actual data.

Let me make an assumption that your tables look like this:

CREATE TABLE Table1 (x INTEGER NOT NULL PRIMARY KEY, y INTEGER NOT
NULL)

CREATE TABLE Table2 (x INTEGER NOT NULL PRIMARY KEY, y INTEGER NOT
NULL)

X is a key and the columns are not nullable.

Try this:

SELECT COALESCE(T1.x,T2.x),
CASE WHEN T1.y > T2.y
THEN T1.y
ELSE COALESCE(T2.y,T1.y)
END
FROM Table1 AS T1
FULL JOIN Table2 AS T2
ON T1.x = T2.x

If X is not unique, then try one of these:

SELECT x, MAX(y)
FROM
(SELECT x,y FROM Table1 UNION ALL
SELECT x,y FROM Table2) AS T
GROUP BY x

SELECT COALESCE(T1.x,T2.x),
CASE WHEN T1.y > T2.y
THEN T1.y
ELSE COALESCE(T2.y,T1.y)
END
FROM
(SELECT x,MAX(y)AS y
FROM Table1
GROUP BY x) AS T1
FULL JOIN
(SELECT x,MAX(y) AS y
FROM Table2
GROUP BY x) AS T2
ON T1.x = T2.x

Hope this helps.

--
David Portas
SQL Server MVP
--

Jul 23 '05 #2
On 17 Jun 2005 02:27:30 -0700, David Portas wrote:
Try this:

SELECT COALESCE(T1.x,T2.x),
CASE WHEN T1.y > T2.y
THEN T1.y
ELSE COALESCE(T2.y,T1.y)
END
FROM Table1 AS T1
FULL JOIN Table2 AS T2
ON T1.x = T2.x

If X is not unique, then try one of these:

SELECT x, MAX(y)
FROM
(SELECT x,y FROM Table1 UNION ALL
SELECT x,y FROM Table2) AS T
GROUP BY x


David,

May I ask why you would choose to go the COALESCE + FULL JOIN route, rather
than just the MAX + GROUP BY? It would seem much more straightforward, and
it seems to me it would work even if X is a unique key. Is there some
advantage to FULL JOIN that I don't understand?
Jul 23 '05 #3
Ross Presser (rp******@NOSPAMgmail.com.invalid) writes:
May I ask why you would choose to go the COALESCE + FULL JOIN route,
rather than just the MAX + GROUP BY? It would seem much more
straightforward, and it seems to me it would work even if X is a unique
key. Is there some advantage to FULL JOIN that I don't understand?


Because there were two tables, and the example included values that
were in 1) Table1 only 2) in Table2 only 3) in both tables. You must
somehow combine these two tables. If X is a unique key, FULL JOIN is
a possible way to go.

Personally my favourite is this the UNION query:

SELECT x, MAX(y)
FROM
(SELECT x,y FROM Table1 UNION ALL
SELECT x,y FROM Table2) AS T
GROUP BY x

It expresses the operation well, it's easy to understand, and you
can easily extended to several tables if that need would appear. And it
does not make any assumptions about the uniqueness of X.

--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #4
Jim
Apologies for the lack of DDL and insert statements, I was in a hurry
and annoyed at myself for not getting it to work so forgot.

Thank you for your input and solutions, I had gone down the route of
the:

SELECT x, MAX(y)
FROM
(SELECT x,y FROM Table1 UNION ALL
SELECT x,y FROM Table2) AS T
GROUP BY x

But had failed to get it to work correctly, it has been way too long
since I last used SQL in anger too much front end coding.

Also interesting to see the coalesce solutions.

Thanks again - Jim

Jul 23 '05 #5
On Fri, 17 Jun 2005 21:56:29 +0000 (UTC), Erland Sommarskog wrote:
It expresses the operation well, it's easy to understand, and you
can easily extended to several tables if that need would appear. And it
does not make any assumptions about the uniqueness of X.


That's exactly the point I was making ... why worry about whether or not X
is unique? It wasn't part of the problem statement.
Jul 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2171
by: Nick | last post by:
Deear All, I would be thankful if you could help me with the following query. I have two tables TableA and TableB TableA Name: David Address: 123 West Side City: New York
6
8135
by: Sven Pran | last post by:
Probably the answer is there just in front of me only awaiting me to discover it, but: 1: I want to build a query that returns all records in one table for which there is no successful "join"...
2
1320
by: Piotr | last post by:
Hi, I have fact tables like following: Sales_2003 Sales_2004 Sales_2005 Sales_2006 As Sales 2006 is deleted and reloaded every day I do not merge all tables every time by executing SELECT...
7
1756
by: Jon Vaughan | last post by:
I have 2 datasets , one returned as a dataset from a webservice and one created client side form the same stored procedure that is returned from the webservice. I then try and merge the data, but...
1
1531
by: mrclash | last post by:
Hello, I have a Database in a SQL Server 2000 where I have different users tables with equal fields like this: id (int) email (varchar) name (varchar) address (varchar) joinedon (datetime)
0
8648
southoz
by: southoz | last post by:
Good ay all , I'm fairly new to access(a little over 5 weeks now). Since I'v started I have picked up a lot of useful information from forums such as this and in doing so will share that information...
5
2502
by: Sam | last post by:
Hi, I have one table like : MyTable {field1, field2, startdate, enddate} I want to have the count of field1 between startdate and enddate, and the count of field2 where field2 = 1 between...
1
1775
by: rebexter | last post by:
I have a list of about 58,000 records which I created by merging numerous smaller lists, each of which contain a certain keyword. What I want to do now is update the master list of 58,000...
30
2930
by: iheartvba | last post by:
Hi, I already have 3 Databases running: A. they all have the same tables and the same structure B. There is no 1 Master table they are all separate tables What I want to do is to merge them...
0
7153
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7371
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7432
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7093
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7517
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5676
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5077
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4743
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
452
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.