我试图只获得每个文件ID的一次出现和最后一次,即我提供的方式,即使我提供了一个FileID,它仍会返回多个。
SELECT
FM.FileNumber, FA.ReceivedDate AS LienSearchOrderDate,
FA1.ReceivedDate AS LienSearchReceivedDate,
DATEDIFF(dd, FA.ReceivedDate, FA1.ReceivedDate) AS TurnTimeDaysLienSearch,
FM.FileID, PC.Name, C.County, P.State, S.Name AS Status,
FM.ClientsFileNumber
FROM dbo.FileMain AS FM
INNER JOIN dbo.FilePartnerRel AS FPR ON FM.FileID = FPR.FileID AND FPR.PartnerTypeID = 10011
INNER JOIN dbo.PartnerCompany AS PC ON FPR.PartnerCompanyID = PC.PartnerCompanyID
LEFT JOIN dbo.FileActions AS FA ON FM.FileID = FA.FileID
LEFT JOIN dbo.FileActions AS FA1 ON FA.FileID = FA1.FileID
LEFT JOIN dbo.ActionDef AS AD ON FA1.ActionDefID = AD.ActionDefID
INNER JOIN dbo.Property AS P ON FA1.FileID = P.FileID
INNER JOIN dbo.County AS C ON P.CountyID = C.CountyID
INNER JOIN dbo.Status AS S ON FM.StatusID = S.StatusID
WHERE FM.FileNumber = 'PA-22440'
and (FM.OpenedDate > '2012-10-01')
AND (FA.ActionDefID = 28)
AND (FA.ReceivedDate IS NOT NULL)
AND (FA.Live = 1) AND (FA1.ActionDefID = 183)
AND (FA1.Live = 1)
Group by FA.ReceivedDate, FM.FileNumber, FA1.ReceivedDate, FM.FileID, PC.Name, C.County,
P.State, S.Name, FM.ClientsFileNumber
Order by 1
我确信我有一些过度使用查询,但我在这里尝试。我可以得到它以获得最低限度的发生,但我想让它拉出每个实例FileNumber。
以下是我得到的输出:
FileNumber LienSearchOrderDate LienSearchReceivedDate TurnTimeDaysLienSearch FileID Name County State Status ClientsFileNumber
PA-22440 38:37.6 NULL NULL 16448 NTIS Pinellas FL Cancelled test
PA-22440 40:08.8 NULL NULL 16448 NTIS Pinellas FL Cancelled test
,预期只是最后一项,仅此而已。
答案 0 :(得分:0)
尝试此查询,如果它是您需要的
SELECT FM.FileNumber, FA.ReceivedDate AS LienSearchOrderDate,
FA1.ReceivedDate AS LienSearchReceivedDate,
DATEDIFF(dd, FA.ReceivedDate, FA1.ReceivedDate) AS TurnTimeDaysLienSearch,
FM.FileID, PC.Name, C.County, P.State, S.Name AS Status,
FM.ClientsFileNumber
FROM dbo.FileMain AS FM
INNER JOIN dbo.FilePartnerRel AS FPR ON FM.FileID = FPR.FileID AND FPR.PartnerTypeID = 10011
INNER JOIN dbo.PartnerCompany AS PC ON FPR.PartnerCompanyID = PC.PartnerCompanyID
LEFT JOIN dbo.FileActions AS FA ON FM.FileID = FA.FileID
LEFT JOIN dbo.FileActions AS FA1 ON FA.FileID = FA1.FileID
LEFT JOIN dbo.ActionDef AS AD ON FA1.ActionDefID = AD.ActionDefID
INNER JOIN dbo.Property AS P ON FA1.FileID = P.FileID
INNER JOIN dbo.County AS C ON P.CountyID = C.CountyID
INNER JOIN dbo.Status AS S ON FM.StatusID = S.StatusID
WHERE FM.FileNumber = 'PA-22440'
and (FM.OpenedDate > '2012-10-01')
AND (FA.ActionDefID = 28)
AND (FA.ReceivedDate IS NOT NULL)
AND (FA.Live = 1) AND (FA1.ActionDefID = 183)
AND (FA1.Live = 1)
AND (FA.ReceivedDate = (SELECT MAX(ReceivedDate) FROM FileActions WHERE ActionDefID = 28 AND ReceivedDate IS NOT NULL AND Live = 1 AND FileID = FM.FileID))
Order by FM.FileNumber
如果您在FileActions表中有一个主键,我希望您拥有该主键,请使用它来匹配正确的记录,而不是将其与ReleaseDate匹配。像这样:
AND FA.PrimaryKey = (SELECT TOP 1 PrimaryKey FROM FileActions WHERE FileID = FM.FileID ORDER BY ReleaseDate DESC)