如果第一个参数失败/同一日期,我想添加第二个参数。我希望location是第二个参数,本例是“location a”。所以在这个例子中:
name date doc info location
=====================================================================
janedoe 7/21 jones 47 a
jonwall 7/1 nick 21 a
name date doc info location
=================================================================
janedoe 7/21 jones 74 b
jonwall 8/31 hall 22 b
结尾应该像这样
name date doc info location
=========================================================================
janedoe 7/21 jones 47 a
jonwall 8/31 hall 22 b
Need help combining columns from 2 tables and keep remaining data in rows based on parameters in sql
答案 0 :(得分:1)
您需要编辑问题。通过回到原始问题的指针很难回溯并提供问题的答案。你应该提供一个完整的问题。但是,我会采取刺。使用作为上一个答案答案的查询,您需要将location desc
或location asc
添加到窗口函数的分区,以便在两个日期匹配时充当决胜局。
另外,请查看MERGE命令。它为类似的问题提供了更清晰的方法。
DECLARE @A TABLE(name NVARCHAR(20),date DATETIME,doc NVARCHAR(20),info NVARCHAR(20),location NVARCHAR(20))
DECLARE @B TABLE(name NVARCHAR(20),date DATETIME,doc NVARCHAR(20),info NVARCHAR(20),location NVARCHAR(20))
INSERT INTO @A SELECT 'janedoe','7/21/2017','jones','47','a'
INSERT INTO @A SELECT 'jonwall','7/1/2017','nick','21','a'
INSERT INTO @B SELECT 'janedoe','7/21/2017','jones','74','b'
INSERT INTO @B SELECT 'jonwall','8/31/2017','hall','22','b'
INSERT INTO @B SELECT 'janedoe','7/21/2017','jones','74','a'
INSERT INTO @B SELECT 'jonwall','8/31/2017','hall','22','c'
;WITH allRows AS (
SELECT * FROM @A
UNION ALL
SELECT * FROM @B
), mostRecent AS (
SELECT *,
ROW_NUMBER() OVER
(PARTITION BY name ORDER BY date DESC, location desc) as rn
FROM allRows
)
SELECT *
FROM mostRecent
WHERE rn = 1