Sql组按日期查询

时间:2017-09-06 08:35:13

标签: sql sql-server

我正在尝试将此结果分组:

ID  TEXT             Table1  FK1    Nodedate
940 bov1             TASKS   48  2016-10-26 15:53:20.247

进入

SELECT  N.ID As ID , n.Text as Text ,Table1 , FK1 ,N.Created as notedate 
FROM NOTES N With(nolock)
LEFT OUTER JOIN NOTELinks NL On(N.id = NL.noteid)
WHERE Table1 = 'TASKS' AND N.IsSystem =0 AND FK1=48  
GROUP BY Table1 , FK1 
order by N.Created desc

有没有办法只用日期分组到一个结果?

当前查询:

.TextBox {
    width: 96%;
    height: 25px;
    border: none;
    padding: 0px 2%;
    font-size: 17px;
    color: #555;
    max-width:200ch;
    word-wrap:break-word;
}

2 个答案:

答案 0 :(得分:2)

你只想要最新的记录吗?

SELECT TOP 1
    N.ID As ID,
    N.Text AS Text,
    Table1,
    FK1,
    N.Created AS notedate 
FROM NOTES N WITH (NOLOCK)
LEFT JOIN NOTELinks NL
    ON N.id = NL.noteid
WHERE
    Table1 = 'TASKS' AND
    N.IsSystem = 0   AND
    FK1 = 48
ORDER BY N.Created DESC

如果您需要查找每个Table1FK1组的最新记录,请考虑使用分析函数:

SELECT t.ID, t.Text, t.Table1, t.FK1, t.notedate
FROM
(
    SELECT TOP 1 N.ID As ID, N.Text as Text, Table1, FK1, N.Created AS notedate,
        RANK() OVER (PARTITION BY Table1, FK1 ORDER BY N.Created DESC) rank
    FROM NOTES N With(nolock)
    LEFT JOIN NOTELinks NL
        ON N.id = NL.noteid
    WHERE Table1 = 'TASKS' AND N.IsSystem = 0 AND FK1 = 48
) t
WHERE t.rank = 1;

我在这里使用RANK而不是ROW_NUMBER,因为两条或更多条记录可能被绑定为最新记录。在这种情况下,上面的查询将返回所有关系。

答案 1 :(得分:0)

我建议您使用ROW_NUMBER(),因为如果要求超过1 FK1,或者您需要OFFSET,则无法使用TOP

SELECT p.* FROM (
    SELECT .....
           ROW_NUMBER() OVER(PARTITION BY n.FK1 ORDER BY n.created DESC) as rnk
    FROM .... // REST OF THE QUERY ) p
WHERE p.rnk = 1

这是动态的,可以返回每个FK1存在的所有最新记录