如何获取数据库表中每个类别的最后插入(日期时间)记录

时间:2011-08-11 11:57:40

标签: sql sql-server

如何获取数据库表中每个类别的最后插入(日期时间)记录

像:

select top 1 from table1, table2

where condition1 ...

and condition2 = case when (@var1 = null) then table2.condition2 else @var1

- 如果未传递特定类别,则适用于所有类别

order by Creation_Date

感谢任何帮助(尤其是示例代码)。提前谢谢。

4 个答案:

答案 0 :(得分:1)

使用GROUP BY,例如

SELECT
  MAX(Creation_Date),
  Category
FROM table
GROUP BY Category

将“将来”添加Creation_Date < your_max_date条件中的所有记录排除到WHERE

答案 1 :(得分:0)

怎么样:

SELECT MAX(Creation_date), category
FROM table1, table2 
WHERE condition1 ..
GROUP BY category

答案 2 :(得分:0)

这将让您返回完整记录。您需要小心GROUP BY,因为它将返回MAX日期,但会返回表中首先遇到的记录。

SELECT MAX(a.dtm_created),a.*
FROM (
       SELECT * FROM table1,table2 WHERE someconditions 
       ORDER BY table1.dtm_created DESC) AS a
GROUP BY a.category

答案 3 :(得分:0)

我会使用分析函数

SELECT *
FROM
(
  SELECT ROW_NUMBER() OVER (PARTITION BY category ORDER BY Creation_Date DESC) RN, *
  FROM table
  WHERE condition1
) T
WHERE T.RN = 1