我有一个包含多个值的合约ID的表。
SELECT contractid
,milestoneid
,DATE
,type
,RANK() OVER (PARTITION BY contractid ORDER BY Milestoneid ASC) AS RankNbr
FROM [TSWDATA].[dbo].t_milestone
WHERE contractid = 1056229
contractid milestoneid date type RankNbr
1056 43269 10/10/15 Full 1
1056 43449 10/26/15 GB 2
1056 43456 10/26/15 Submit for Funding 3
1056 43463 10/26/15 Cleared 4
我需要加入主合约表并且仅在价值' GB'是最大的里程碑。
我可以在where子句中执行此操作吗?
答案 0 :(得分:0)
这对你有用吗?
SELECT contractid
,milestoneid
,DATE
,type
,RANK() OVER (PARTITION BY contractid ORDER BY Milestoneid ASC) AS RankNbr
FROM [TSWDATA].[dbo].t_milestone
WHERE EXISTS (SELECT TOP (1) *
FROM SubTable AS s
WHERE s.type = 'GB'
AND s.contractID = [TSWDATA].[dbo].t_milestone.contractid
ORDER BY s.milestoneID DESC
)
AND contractid = 1056229
答案 1 :(得分:0)
如果您需要合同表中的记录,那么您可以加入您的排名查询。只需将您的订单更改为DESC,因此RankNbr 1将是最大里程碑
SELECT *
FROM [TSWDATA].[dbo].t_contract c
JOIN (
SELECT contractid
,type
,RANK() OVER (PARTITION BY contractid ORDER BY Milestoneid DESC) AS RankNbr
FROM [TSWDATA].[dbo].t_milestone
) ms ON ms.contractid = c.contractid
WHERE
--contractid = 1056229 AND
ms.RankNbr = 1 AND ms.type = 'GB'