简体   繁体   English

如何反转来自已包含ORDER BY的SQL查询的表

[英]How to reverse the table that comes from SQL query which already includes ORDER BY

Here is my query: 这是我的查询:

SELECT TOP 8 id, rssi1, date
FROM history
WHERE (siteName = 'CCL03412') 
ORDER BY id DESC

This the result: 结果如下:

在此处输入图片说明

How can I reverse this table based on date (Column2) by using SQL? 如何使用SQL根据日期(列2)反转此表?

You could simply use a sub-query. 您可以简单地使用子查询。 If you apply a TOP clause the nested ORDER BY is allowed: 如果您应用TOP子句,则允许嵌套的ORDER BY

SELECT X.* FROM(
  SELECT TOP 8 id, Column1, Column2
  FROM dbo.History
  WHERE (siteName = 'CCL03412') 
  ORDER BY id DESC) X
ORDER BY Column2

Demo 演示

The SELECT query of a subquery is always enclosed in parentheses. 子查询的SELECT查询始终括在括号中。 It cannot include a COMPUTE or FOR BROWSE clause, and may only include an ORDER BY clause when a TOP clause is also specified . 它不能包含COMPUTE或FOR BROWSE子句,并且仅当还指定了TOP子句时才可以包括ORDER BY子句

Subquery Fundamentals 子查询基础知识

You can use the first query to get the matching ids, and use them as part of an IN clause: 您可以使用第一个查询来获取匹配的ID,并将其用作IN子句的一部分:

SELECT id, rssi1, date
FROM history
WHERE id IN
(
    SELECT TOP 8 id
    FROM history
    WHERE (siteName = 'CCL03412') 
    ORDER BY id DESC
)
ORDER BY date ASC

didn't run it, but i think it should go well 没有运行它,但我认为它应该运行良好

WITH cte AS 
(
    SELECT id, rssi1, date, RANK() OVER (ORDER BY ID DESC) AS Rank
    FROM history
    WHERE (siteName = 'CCL03412')
)
SELECT id, rssi1, date
FROM cte
WHERE Rank <= 8
ORDER BY Date DESC

try the below : 请尝试以下方法:

select * from (SELECT TOP 8 id, rssi1, date
FROM history
WHERE (siteName = 'CCL03412') 
ORDER BY id DESC ) aa order by aa.date DESC

I have not run this but i think it will work. 我没有运行它,但我认为它将起作用。 Execute and let me know if you face error 执行并让我知道您是否遇到错误

select id, rssi1, date from (SELECT TOP 8 id, rssi1, date FROM history WHERE (siteName = 'CCL03412') ORDER BY id DESC) order by date ; 选择ID,rssi1,日期,从(SELECT TOP 8 id,rssi1,date from history WHERE(siteName ='CCL03412')ORDER BY ID DESC)按日期排序;

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

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