SQL嵌套查询MAX(日期)

时间:2013-10-15 17:31:44

标签: sql sql-server

有没有更好的方法来构建我的SQL?

我想为每个客户选择最近的事件。事件由where子句过滤。如果客户端没有满足where子句的事件,我也想注意一下。

EVENT_DATE EVENT_STAFF     EVENT_TYPE  
1/1/2013   Myley_Cyrus     Music_Awards
3/1/1947   Albert_Einstein Noble_Prize

目前,我这样做:  1.选择客户端ID。  2.选择这些客户端的所有事件。  2B。过滤这些事件。  3.选择最近过滤的事件或报告“X”(没有事件符合条件)。

问题是MAX(e_date)返回多行,而不仅仅是最近的事件(每个e_staff / e_type组合一行)。

/* STEP #3: SELECT MOST RECENT FILTERED EVENT FOR EACH CLIENT */
SELECT          MAX(e_date), e_staff, e_type
FROM            client INNER JOIN events ON events.e_case_no = client.c_id
WHERE           events.id IN (
    /* STEP #2: SELECT FILTERED EVENTS FOR THOSE CLIENTS */
    SELECT events.id
    FROM events INNER JOIN client ON e_case_no = c_id
    WHERE client.c_id IN (
        /* STEP #1: SELECT CLIENTS */                                                               
       SELECT client.c_id
       ...
       /* STEP #1 END */
    )
    AND ... --FILTER THE EVENTS 
    /* STEP #2 END */
)
GROUP BY e_staff, e_type
/* STEP #3 END */

谢谢!

2 个答案:

答案 0 :(得分:1)

尝试查看row_number()窗口函数

 select * 
 from
 (
      select *,
          row_number() over (partition by e_staff, e_type order by e_date desc) rn
      from yourfilteredrows
 ) v
 where rn = 1

答案 1 :(得分:0)

我认为这应该有用

Select e.id, staff, type, c.Name from Events e inner join
(Select max(e_date) Date, clientid from Events group by clientid) x
on x.Date = e.e_date and x.clientId = e.ClientId
inner join Clients c on c.id = x.ClientId