我有下表:
ClientId | CalculationDate | TransactedAmount |
1 13/02/2015 3
1 14/02/2015 3
2 14/02/2015 5
3 15/03/2015 6
2 15/03/2015 5
因此,我想要包含ClientId的表和从那时起传递的最小月数 每个clientId交易最大金额。 我怎么能这样做?
答案 0 :(得分:2)
SELECT DISTINCT ClientId , MaxAmount.TransactedAmount , DATEDIFF(MONTH,MaxAmount.CalculationDate ,getdate())
FROM TABLENAME T1
CROSS APPLY(SELECT TOP 1 TransactedAmount ,CalculationDate
FROM TABLENAME T2
WHERE T1.ClientId = T2.ClientId
ORDER BY TransactedAmount DESC) MaxAmount
答案 1 :(得分:0)
使用像Row_Nummber()这样的Window函数我们可以实现相同的
;With cte(ClientId , CalculationDate , TransactedAmount )
AS
(
SELECT 1,'13/02/2015',3 UNION ALL
SELECT 1,'14/02/2015',3 UNION ALL
SELECT 2,'14/02/2015',5 UNION ALL
SELECT 3,'15/03/2015',6 UNION ALL
SELECT 2,'15/03/2015',5
)
SELECT ClientId , CalculationDate,TransactedAmount From
(
SELECT ClientId , CalculationDate ,MAX(TransactedAmount)OVER(Partition by ClientId Order by CalculationDate) As TransactedAmount ,
ROW_NUMBER()OVER(Partition by ClientId Order by CalculationDate) AS RNo From cte
)Dt
WHERE Dt.RNo=1