根据MAX日期选择行(多个表)

时间:2014-05-12 21:11:43

标签: sql sql-server reporting-services greatest-n-per-group ssrs-2008-r2

我正在尝试为每个 service_id 创建一个返回 accountservice_id 并且MAX fromdate 的查询。每个 service_id 都可以绑定多个 accountservice_id ,不幸的是MAX accountservice_id 并不总是MAX fromdate

例如:

service_id   accountservice_id       fromdate
---------------------------------------------------
3235           1081         2009-12-01 12:00:00
3235           1007         2013-03-15 12:00:00
3235           2104         2012-10-25 12:00:00
3340           1047         2009-12-15 13:50:00

以下是我当前的查询。

SELECT  service.service_id, accountservice.accountservice_id, accountservice.fromdate
FROM    service 
INNER JOIN accountservice ON service.service_id = accountservice.service_id
WHERE (service.servicetype_id IN (1, 74571, 74566))
ORDER BY service.service_id, accountservice.fromdate

3 个答案:

答案 0 :(得分:2)

CTE + ROW_NUMBER()是一个获胜的组合。

;with cte as (
   SELECT service_id,
          accountservice_id,
          max_date_rank = row_number() 
                          over(partition by service_id 
                               order by fromdate desc)
   FROM   service
)
SELECT *
FROM   cte
WHERE  max_date_rank = 1

ETA:使用派生表:

SELECT * 
FROM (
    SELECT service_id,
           accountservice_id,
           max_date_rank = row_number() 
                           over(partition by service_id 
                                order by fromdate desc)
    FROM   service
) t
WHERE t.max_date_rank = 1

答案 1 :(得分:1)

您可以执行子查询来获取数据。使用一个查询获取service_id的最大fromdate,然后将其加入搜索与service_id和max fromdate匹配的accountservice_id。

SELECT maxfromdate.service_id, correct_account.accountservice_id, maxfromdate.maxfromdate
FROM (SELECT 
    Service.service_id, 
    MAX (accountservice.fromdate) AS maxfromdate 
    FROM service 
    JOIN accountservice ON service.service_id = accountservice.service_id) 
    GROUP BY Service.service_id) maxfromdate
JOIN (SELECT 
    Service.service_id, 
    accountservice.accountservice_id, 
    accountservice.fromdate 
    FROM service 
    JOIN accountservice ON service.service_id = accountservice.service_id
)correct_account ON
     (maxfromdate.service_id = correct_account.service_id 
      AND maxfromdate.maxfromdate = correct_account.fromdate)

答案 2 :(得分:0)

您可以创建临时表以首先获取service_id的更新日期:

Select service.service_id, max(accountService.fromdate) fromdate
into #serviceMaxDate from service 
inner join accountService ON service.service_id = accountservice.service_id
group by service.service_id

之后,得到它:

SELECT  service.service_id, accountservice.accountservice_id, service.fromdate
FROM    #serviceMaxDate service
INNER JOIN accountservice ON service.service_id = accountservice.service_id
ORDER BY service.service_id, accountservice.fromdate