如何编写这个SQL语句

时间:2009-04-01 15:38:14

标签: sql sql-server

table1有3列:

Id UserName SubmittedDate
1 Joe 1/1/2006
2 Joe 1/1/2007
3 Nat 1/1/2008
4 Pat 1/1/2009

我想要归还:

Id用户名
2乔
3 Nat 4帕特

我只想要一张Joe的记录,最近的记录。

如何撰写此查询?感谢

5 个答案:

答案 0 :(得分:4)

SELECT  Id, UserName, SubmittedDate
FROM    (
        SELECT  Id, UserName, SubmittedDate,
                ROW_NUMBER() OVER (PARTITION BY UserName ORDER BY SubmittedDate DESC) rn
        FROM    table1
        ) q
WHERE rn = 1

答案 1 :(得分:3)

SELECT MAX(ID), UserName
FROM table
GROUP BY UserName

请注意,这假设较高的ID意味着以后。它不直接在“提交日期”字段中查询。为此,使用Quassnoi更为复杂的一个:)

答案 2 :(得分:1)

仅使用标准SQL:

SELECT Id, UserName
FROM table1
JOIN (
    SELECT UserName, MAX(SubmittedDate) AS MaxDate
    FROM table1
    GROUP BY UserName
    ) AS MaxDateTable ON table1.UserName = MaxDateTable.UserName
WHERE SubmittedDate = MaxDate

答案 3 :(得分:1)

以下是三种可能的解决方案。给他们一个尝试,看看哪个更适合您的数据和情况。请注意,在用户名具有两个相同的submitted_date值的情况下,结果可能与您期望的不同。

SELECT
    T1.id,
    T1.username
FROM
    My_Table T1
INNER JOIN 
  (
   SELECT username, MAX(submitted_date) 
   FROM My_Table T2 GROUP BY username
  ) SQ 
    ON SQ.username = T1.username AND SQ.submitted_date = T1.submitted_date

SELECT
    T1.id,
    T1.username
FROM
    My_Table T1
WHERE
    NOT EXISTS 
    (
      SELECT * 
      FROM
         My_Table T2 
      WHERE
         T2.username = T1.username AND
         T2.submitted_date > T1.submitted_date
    )

SELECT
    T1.id,
    T1.username
FROM
    My_Table T1
LEFT OUTER JOIN My_Table T2 ON
    T2.username = T1.username AND
    T2.submitted_date > T1.submitted_date
WHERE
    T2.id IS NULL

答案 4 :(得分:0)

扯掉@Quassnoi,但我喜欢传授使用CTEs来代替子查询和大多数视图。

WITH
query1 as(
    SELECT  Id, UserName, SubmittedDate,
            ROW_NUMBER() OVER (PARTITION BY UserName ORDER BY SubmittedDate DESC) rn
    FROM    table1
        )

SELECT  Id, UserName, SubmittedDate
FROM   query1
WHERE rn = 1