I have two tables:
TABLE_A TABLE_B
Fields: Trans Amend Trans Amend
data: 100 0 100 0
100 1
110 0
120 0
120 1
130 0 130 0
130 1
140 0 140 0
150 0 150 0
150 1 150 1
150 2
What I want is a table (view) that will combine (union) these to tables but will only show the highest Amend for each Trans
Looking for this as the answer:
Fields: Trans Amend
data: 100 1
110 0
120 1
130 1
140 0
150 2
Then to make it harder, I would like to know if there is a way I can tell from which table the data is coming from. Table A always wins when Record A and Record B are equal Looking for this as the answer:
Fields: Trans Amend WhichTBL
data: 100 1 Table_A
110 0 Table_A
120 1 Table_B
130 1 Table_B
140 0 Table_A
150 2 Table_A
I know a UNION can't be done to get this result.
If Amend only has value 1 and 0 then the first question can be done
the secound question would be
What if you added a string in your select and aliased it as a column?
In Teradata SQL you would do the following, not sure about SQL Server:
A version using Lucero's suggestion if your SQL doesn't have a QUALIFY clause:
I want to offer that you can do this with a join and aggregation, using standard SQL:
would this work?
Lucero's point below is correct, the min(src) would be on the global set, not the related max()
I think you'd have to combine the source and table values into one column you can max. In your example, adding 1 to the value is all you need to distinguish the sources, like:
but you could add 100, or multiply by a big value, or whatever works with your data. The idea is to combine the two pieces of information, the amend value and the source, into one column.
Then, after the information is combined, you get the max of that value, then strip off the source flag by uncombining them (subtracting 1, dividing by 100, whatever)
OK, here's what I got: