473,750 Members | 2,557 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 1540
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,T 2.x),
CASE WHEN T1.y > T2.y
THEN T1.y
ELSE COALESCE(T2.y,T 1.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,T 2.x),
CASE WHEN T1.y > T2.y
THEN T1.y
ELSE COALESCE(T2.y,T 1.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,T 2.x),
CASE WHEN T1.y > T2.y
THEN T1.y
ELSE COALESCE(T2.y,T 1.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******@NOSPA Mgmail.com.inva lid) 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****@sommarsk og.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
2180
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
8164
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" in another table but I have not found what the field criteria should look like? 2: And if/when I succeed I should further like to build a new record (with
2
1332
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 INTO command.
7
1770
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 they dont seem to merge. When I return a single table , this method works fine, but im returning 3 tables and the merge isnt happening. Is there anyway to find out how I can why a merge isnt occuring, as the merge doesnt return any errors,
1
1539
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
8664
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 with others. I have seen many request for information on mail merging an how to send data to word documents this is something I have put together with the answers given by others and I hope this will help a few newbies , I know there are easier ways...
5
2514
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 startdate and enddate, all in the same query.
1
1783
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 records so that each line shows which of one or more keywords that record contains. For example, the original source tables contain the following fields: DocID, Keyword where DocID uniquely identifies each record no matter what table that record...
30
2967
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 into 1 Master Table to be able to generate reports etc. An append query will not suffice because some fields get updated in the orginial databases. I have looked into database replication and I think it would work. I have considered the following...
0
9583
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9342
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9256
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6081
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4716
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4888
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3323
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2807
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2226
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.