问题
I am needing some help with this! I have been steered toward the intersect function, but it seems limited as it only matches and returns matched values. I am trying to combine 2 tables on a common column value and return the rows based on a date parameter. Is this even possible using SQL? Thanks in advance!
My starting tables look like this:
name date doc info
janedoe 7/21 jones 47
jonwall 7/1 nick 21
name date doc info
janedoe 6/21 jones 74
jonwall 8/31 hall 22
I want to combine these rows by duplicate name. And keep the remaining data based on most recent date. so the end result should look like this.
name date doc info
janedoe 7/21 jones 47
jonwall 8/31 hall 22
Is there anyway anyone could help me on this???? I am currently using SQLExpress
回答1:
WITH allRows AS (
SELECT * FROM tableA
UNION ALL
SELECT * FROM tableB
), mostRecent AS (
SELECT *,
ROW_NUMBER() OVER
(PARTITION BY name ORDER BY date DESC) as rn
FROM allRows
)
SELECT *
FROM mostRecent
WHERE rn = 1
You should have some ID
column, otherwise you are risking having two person with same name.
来源:https://stackoverflow.com/questions/45442337/need-help-combining-columns-from-2-tables-and-keep-remaining-data-in-rows-based