0

有没有更好的方法来构建我的 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 */

谢谢!。

4

2 回答 2

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
于 2013-10-15T17:35:51.230 回答
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
于 2013-10-16T20:38:46.960 回答