SQL选择前一行的条件

时间:2012-03-15 11:57:08

标签: sql sql-server tsql select

如何写这样的选择:

SELECT filename, username, date_time, field1, field2... FROM... JOIN... WHERE...
UNLESS user_downloaded_this_file_today_already

我想忽略同一用户在同一天下载的文件。数据示例:

12 | file1.jpg | barney | 2012-03-15 12:50:10 | ...
13 | file1.jpg | roger  | 2012-03-15 13:50:10 | ...
14 | file2.jpg | barney | 2012-03-15 14:50:10 | ...
15 | file1.jpg | barney | 2012-03-15 15:50:10 | ...

如何编写一个忽略第4行的SELECT?相同的文件名,相同的用户,日差异<这有可能吗?

3 个答案:

答案 0 :(得分:4)

为了在当天允许重复,我认为以下就足够了:

select filename, username, date_time, field1, field2
  from yourtable t
 where not exists (
    select 1 
      from yourtable
     where t.filename = filename
       and t.username = username
       and trunc(t.date_time) = trunc(date_time)
       and t.date_time > date_time)
 order by t.date_time

这将每天返回每个文件/用户组合的第一个请求。

答案 1 :(得分:2)

只需使用SELECT DISTINCT(假设您不需要数字列,因为它不在您的选择中):

SELECT DISTINCT  FileName,
                 UserName,
                 Date_Time
FROM             [YourTable]

如果您的Date_Time列包含时间而不只是00:00:00,则您需要删除DISTINCT正常工作的时间:

SELECT DISTINCT  FileName,
                 UserName,
                 CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, Date_Time))) AS Date_Time
FROM             [YourTable]

这是an example of the date stripping in action

答案 2 :(得分:1)

SELECT filename, username, date_time, field1, field2
FROM (
  SELECT filename, username, date_time, field1, field2,
  ROW_NUMBER() OVER (ORDER BY username,filename, CONVERT(date,date_time)) AS RN,
  RANK() OVER (ORDER BY username,filename, CONVERT(date,date_time)) AS R

  FROM [table]
) A
WHERE A.RN = A.R