使用SQL查询来查找最后一天的代码

时间:2016-07-12 09:15:55

标签: sql sql-server

我想运行查询以找出每个公司使用代码的最后一天。

MAX

我想将T1.date添加到DateValue(Str(T1.period) & Str(T1.yr)) 但不确定sytax ......或类似内容

也许我可以通过连接T1.period&来创建一个DATE字段。 T1,你可能会遇到语法......

CREATE PROC DeleteChildWithParent(@ID BIGINT)
AS

;WITH ChildToDelete AS (
    SELECT  id, CAST(1 AS INT) AS ChildLevel
    FROM    ENTITY
    WHERE   id = @ID 
    UNION ALL
    SELECT  e.id, C.ChildLevel + 1
    FROM    ENTITY E
            JOIN ChildToDelete C ON e.PARENT_ID = C.ID AND E.PARENT_ID <> E.ID
)

SELECT  id, ROW_NUMBER() OVER (ORDER BY ChildLevel DESC) Ord
INTO    #ChildToDelete
FROM    ChildToDelete

DECLARE @count INT = 1, @max INT = @@ROWCOUNT;

WHILE @count <= @max
BEGIN
    DELETE ENTITY WHERE id = (SELECT id FROM #ChildToDelete WHERE Ord = @count);
    SET @count = @count + 1;
END;
GO

非常感谢!

4 个答案:

答案 0 :(得分:3)

在日期降序处订购表格,并仅保留第一行:

SELECT TOP 1 T1.comp, T1.code, T1.date
FROM T1
ORDER BY T1.date DESC

答案 1 :(得分:0)

您需要一个聚合函数。你可以在这里找到更多细节: http://www.sqlcourse2.com/agg_functions.html

平均时间尝试:

SELECT T1.comp, max(T1 date)
FROM T1
GROUP BY t1.comp

答案 2 :(得分:0)

根据对@ThomasG answer的评论,我假设您希望每个def stuff([head | _]) when is_list(head) do something end 的最大值超过300条记录?

如果是,请使用compGROUP BY

HAVING

答案 3 :(得分:0)

试试这个,

SELECT T1.comp, T1.code, MAX(T1.date) AS LastDate
FROM T1
GROUP BY T1.comp, T1.code