SQL查询-在多ID查询中,每个ID仅选择500个条目?

时间:2018-08-07 16:06:31

标签: sql sql-server

我当前的查询如下:

SELECT TOP 500
    n.NodeID as solarwinds_id,
    n.NodeName,
    n.Syslogs.MessageID,
    n.Syslogs.SysLogSeverity,
    n.Syslogs.Message,
    TOLOCAL(n.Syslogs.DateTime) as DateTime
FROM
    Orion.Nodes n
WHERE
    (n.Syslogs.DateTime > '2018-08-06 15:46:23.028792') AND n.NodeID IN (1845, 524, 38, 794, 35, 36)
ORDER BY
    n.Syslogs.DateTime DESC

但是我很快意识到,我只能从整个订购日期中获得前500个条目,也就是说,如果ID 1845有500个条目,我只会获得该ID,而没有其他。

在SQL查询中,每个ID是否有可能获得500个结果? (如果有500个)

谢谢

3 个答案:

答案 0 :(得分:0)

您可以使用row_number()

SELECT n.NodeID as solarwinds_id, n.NodeName, n.Syslogs.MessageID,
       n.Syslogs.SysLogSeverity, n.Syslogs.Message, TOLOCAL(n.Syslogs.DateTime) as DateTime
FROM (SELECT n.*,
             ROW_NUMBER() OVER (PARTITION BY n.NodeId ORDER BY n.Syslogs.DateTime DESC) as seqnum
      FROM Orion.Nodes n
      WHERE n.Syslogs.DateTime > '2018 15:46:23.028792' AND
            n.NodeID IN (1845, 524, 38, 794, 35, 36)
     ) n
WHERE seqnum <= 500
ORDER BY n.Syslogs.DateTime DESC;

答案 1 :(得分:0)

您当前的语法建议SQL Server,要使每个500获得ID个结果,您需要row_number()函数:

SELECT n.NodeID as solarwinds_id, n.NodeName, n.Syslogs.MessageID,
       n.Syslogs.SysLogSeverity, n.Syslogs.Message, TOLOCAL(n.Syslogs.DateTime) as DateTime
FROM (SELECT n.*, ROW_NUMBER() OVER (PARTITION BY NodeId ORDER BY Syslogs.DateTime DESC) as seq
      FROM Orion.Nodes n
      WHERE Syslogs.DateTime > '2018 15:46:23.028792' AND
            NodeID IN (1845, 524, 38, 794, 35, 36)
     ) n
WHERE seq <= 500
ORDER BY n.Syslogs.DateTime DESC;

答案 2 :(得分:0)

您可以使用Rank()几乎所有数据库都具有此功能。

您可以使用CTE或临时表或子查询

以下是CTE的示例。

select * from ( SELECT 
    n.NodeID as solarwinds_id,
    n.NodeName,
    n.Syslogs.MessageID,
    n.Syslogs.SysLogSeverity,
    n.Syslogs.Message,
    TOLOCAL(n.Syslogs.DateTime) as DateTime,
    RANK() OVER (PARTITION BY n.NodeID ORDER BY  n.Syslogs.DateTime DESC) as rnk FROM
    Orion.Nodes n WHERE
    (n.Syslogs.DateTime > '2018-08-06 15:46:23.028792') AND n.NodeID IN (1845, 524, 38, 794, 35, 36))

as a  where rnk <=500