本文介绍了如何编写T-SQL查询以为每个客户端选择前1条记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的脚本,我试图获取每个客户端的最新记录.如何在TSQL中执行此操作?这是我目前的代码,但是,这仅选择了一条记录.一条记录显示所有客户机而不是每个客户机的最新记录!我该如何重新制定呢?

I have a simple script that I am trying to get the most recent records per client on. How do I do this in TSQL? This is my code currently, however, this is only selecting one record total. This one record displays most recent record for ALL clients and not EACH client! How can I reformulate this please?

SELECT TOP 1
C.ClientID, actual_date
From ClientRecords C
WHERE (@ClientID is NULL or C.Client_ID = @ClientID)
Group by C.ClientID, actual_date
ORDER BY C.actual_date

推荐答案

汇总通过在 actual_date 上使用 MAX()函数<

SELECT  C.ClientID, MAX(actual_date) max_DATE
From    ClientRecords C
WHERE   (@ClientID is NULL or C.Client_ID = @ClientID)
Group   by C.ClientID
ORDER   BY C.actual_date

这篇关于如何编写T-SQL查询以为每个客户端选择前1条记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 04:51