如何按所有人联接表的订单

时间:2019-05-29 20:32:40

标签: sql sql-server

我正在尝试[联盟] 5个表格和[日期/时间]的“排序依据”。这很好用,但是问题是结果是225000+行。这将不适合excel。

我试图通过“选择顶部#”来限制行数,这限制了大小,但是顶部是数据中的第一个,我需要最后一个或最新的数据

SELECT top 1000 [Timestmp]
 ,[Audience]
 ,[Severity]
,[Verbosity]
,[UserFullName]
FROM [PD_SQL_DB].[dbo].[Client1_DiagList]
wHERE [aUDIENCE]='8' AND [SEVERITY] = '4'AND [VERBOSITY] = '0'
Union
SELECT top 1000 [TimeStmp]
,[MessageText]
,[Audience]
,[Severity]
,[Verbosity]
,[UserFullName]
FROM [PD_S`enter code here`QL_DB].[dbo].[Client2_DiagList]
WHERE [AUDIENCE]='8' AND [SEVERITY] = '4'AND [VERBOSITY] = '0'
 Order by [TimeStmp] desc

使用Query只会给我前1000行。通过desc限制数量或行数和顺序的另一种方法是什么。

1 个答案:

答案 0 :(得分:2)

您可以将UNION嵌套在另一个SELECT中,然后在其中进行TOP / ORDER BY

SELECT TOP 1000 * 
FROM (
    SELECT [Timestmp]
      ,[Audience]
      ,[Severity]
      ,[Verbosity]
      ,[UserFullName]
    FROM [PD_SQL_DB].[dbo].[Client1_DiagList]
    WHERE [aUDIENCE]='8' AND [SEVERITY] = '4'AND [VERBOSITY] = '0'

    Union

    SELECT [TimeStmp]
      ,[MessageText]
      ,[Audience]
      ,[Severity]
      ,[Verbosity]
      ,[UserFullName]
    FROM [PD_S`enter code here`QL_DB].[dbo].[Client2_DiagList]
    WHERE [AUDIENCE]='8' AND [SEVERITY] = '4'AND [VERBOSITY] = '0'
) t
ORDER BY [TimeStmp] DESC