Need help combining columns from 2 tables and keep remaining data in rows based on parameters in sql

血红的双手。 提交于 2019-12-13 03:42:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!