简体   繁体   English

SQL按日期分组

[英]Sql group by date query

I am trying to group this result: 我正在尝试将此结果分组:

ID  TEXT             Table1  FK1    Nodedate
940 bov1             TASKS   48  2016-10-26 15:53:20.247
938 foxxxxdsx        TASKS   48  2016-10-26 15:49:15.083
937 test2            TASKS   48  2016-10-26 15:24:32.667
936 test             TASKS   48  2016-10-26 15:24:20.277
889 <>asdasdsa       TASKS   48  2016-09-19 11:23:02.083
600 sadadasasdadsa   TASKS   48  2016-08-29 15:03:11.680

Into just 变成公正

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

is there a way to group to one result with just the date ? 有没有一种方法可以只用日期将结果分组?

current query: 当前查询:

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

Do you just want the most recent record? 您是否只想要最新记录?

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

If you need to find the latest record for each Table1 and FK1 group then consider using an analytic function: 如果需要查找每个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;

I used RANK here rather than ROW_NUMBER in the event that two or more records might be tied for being the latest record. 如果两个或多个记录可能是最新记录,那么我在这里使用RANK而不是ROW_NUMBER In this case, the above query would return all ties. 在这种情况下,以上查询将返回所有联系。

I advise on using ROW_NUMBER() , because if the requirement is for more than 1 FK1 , or you need an OFFSET then it can't be done with TOP : 我建议使用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

This is dynamic to return all the most recent records for every FK1 exists 动态返回每个FK1存在的所有最新记录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM