仅选择最旧的唯一记录

时间:2015-04-08 12:06:22

标签: sql sql-server tsql

以下代码应该 从2个数据库中的多个表中获取多个值 但是当我试图实施时 T-SQL select rows by oldest date and unique category问题的解决方案我遇到了一个错误,我的代码的最后一行会说"'的错误语法'。'

--Create Table #tmp2(FK_clientids varchar(50))
--Create table #tmp (phonenums varchar(50))
Delete from #tmp2
Delete from #tmp
Use Database2
INSERT INTO #tmp2
SELECT fk_clientid
FROM DM_ClientApplicants
where DM_ClientApplicants.FK_ApplicationID in (39155)
Use Database2
INSERT INTO #tmp
Select phonenum2 from DM_PhoneNumbers
where FK_ApplicationID in 
(
   Select FK_clientIDs from #tmp2
)
INSERT INTO #tmp
Select PhoneNum1 from DM_PhoneNumbers
where FK_ApplicationID in 
(
   Select FK_clientIDs from #tmp2
)
INSERT INTO #tmp
Select PhoneNum2 from DM_PhoneNumbers
where FK_ApplicationID in 
(
   Select FK_clientIDs from #tmp2
)

INSERT INTO #tmp
Select PhoneNum3 from DM_PhoneNumbers
where FK_ApplicationID in 
(
   Select FK_clientIDs from #tmp2
)
INSERT INTO #tmp
Select Partnerphonehome from DM_PhoneNumbers
where FK_ApplicationID in 
(
   Select FK_clientIDs from #tmp2
)
INSERT INTO #tmp
Select Partnerphonemobile from DM_PhoneNumbers
where FK_ApplicationID in 
(
   Select FK_clientIDs from #tmp2
)
INSERT INTO #tmp
Select Partnerphonework from DM_PhoneNumbers
where FK_ApplicationID in 
(
   Select FK_clientIDs from #tmp2
)
Use Database1
Select PhoneNum,sourcetable,c.FK_ApplicationID,SolRef,DT.Subject,dt.CreatedDate 
from (select PhoneNum,sourcetable,c.FK_ApplicationID,SolRef,DT.Subject,dt.CreatedDate,
             row_number() over(partition by OrderNO order by dt.CreatedDate desc) rn 
      from Dial D
      join Database2.dbo.DM_PhoneNumbers P on PhoneNum collate Latin1_General_CI_AS = PhoneNum1
      join Database2.dbo.DM_ClientApplicants C on P.FK_ApplicationID = C.FK_ClientID
      join Database2.dbo.DM_Sol S on C.FK_ApplicationID = S.FK_ApplicationID
      join Database2.dbo.DM_ApplicationDetails AD on AD.FK_ApplicationID = S.FK_ApplicationID
      join Database2.dbo.Tasks DT on DT.FK_ApplicationID = S.FK_ApplicationID
where PhoneNum in
(Select phonenums from #tmp)

更新:所以支架靠近" RN"是开放的,但如果我试图关闭它,其余的陈述不明白,任何人都知道为什么?

1 个答案:

答案 0 :(得分:1)

你的SQL的结尾应该是:

Use Database1
Select PhoneNum,sourcetable,FK_ApplicationID,SolRef,Subject,CreatedDate 
from 
(
    select PhoneNum,sourcetable,c.FK_ApplicationID,SolRef,DT.Subject,dt.CreatedDate
    ,row_number() over(partition by OrderNO order by dt.CreatedDate desc) rn 
    from Dial D
    join Database2.dbo.DM_PhoneNumbers P on PhoneNum collate Latin1_General_CI_AS = PhoneNum1
    join Database2.dbo.DM_ClientApplicants C on P.FK_ApplicationID = C.FK_ClientID
    join Database2.dbo.DM_Sol S on C.FK_ApplicationID = S.FK_ApplicationID
    join Database2.dbo.DM_ApplicationDetails AD on AD.FK_ApplicationID = S.FK_ApplicationID
    join Database2.dbo.Tasks DT on DT.FK_ApplicationID = S.FK_ApplicationID
    where PhoneNum in
    (
        Select phonenums from #tmp
    )
)a -- add