如何为此用例编写SQL查询?

时间:2018-04-30 12:23:26

标签: sql

假设我有一个包含三个字段的表格:event_nameevent_timestamp event_result。每一行都是event_name发生的事件 event_timestamp,其中有一些event_result。例如:

 event_name | event_timestamp  | event_result
 -------------------------------------------
 event_a    | 2018-04-29 00:00 | result_x1
 event_a    | 2018-04-29 00:00 | result_x2
 event_b    | 2018-04-29 00:00 | result_x1
 event_a    | 2018-04-29 00:00 | result_x3
 event_b    | 2018-04-29 00:00 | result_x3

现在我需要一个SQL查询来在event_timestamp的给定范围内为每个 event_name选择最新 event_timestamp的行

你会怎么写这样的查询?我想它应该是适用于任何合理的SQL数据库的标准SQL。

6 个答案:

答案 0 :(得分:2)

使用subquery

select * 
from table t
where event_timestamp = (select max(event_timestamp) 
                         from table 
                         where event_name = t.event_name);

而且,一般来说,最有效的方法是使用排名功能(如果支持)

select * from (
      select *,
             row_number() over (partition by event_name order by event_timestamp desc) Seq 
      from table t
      where  event_timestamp between @start and @end
) t
where Seq = 1;

答案 1 :(得分:1)

最便携的解决方案可能是:

SELECT    E.*
FROM      Event E
INNER JOIN (
             SELECT  event_name 
             ,       MAX(event_timestamp) MAX_DT
             FROM    Event 
             WHERE   event_timestamp <= @SomeDate
                  AND event_timestamp > @SomeOtherDate
             GROUP BY event_name 
           ) MAXED
        ON MAXED.event_name = E.event_name 
        AND MAXED.MAX_DT = E.event_timestamp

答案 2 :(得分:0)

类似的东西:

SELECT event_name
    ,MAX(event_timestamp)
FROM myTable
WHERE event_timestamp BETWEEN date1
        AND date2
GROUP BY event_name

答案 3 :(得分:0)

您可以使用group by并包含max event_timestamp 在MSSQL中:

select
event_name
, MAX(event_timestamp)
from [table_name]
where event_timestamp between '2018-04-20' and '2018-04-30'
group by event_name

答案 4 :(得分:0)

SELECT * FROM `your_table` 
WHERE `event_timestamp` BETWEEN 'your_start_range'AND 'your_end_range'
GROUP BY `event_name`
ORDER BY `event_timestamp` DESC
LIMIT 1;

答案 5 :(得分:0)

此代码适用于ms sql

SELECT *
FROM
    (SELECT
        *, ROW_NUMBER() OVER(PARTITION BY event_name ORDER BY event_timestamp DESC) AS row_no
     FROM    Event 
     WHERE
        event_timestamp BETWEEN @BeginDate AND @EndDate) as tbl
WHERE row_no = 1