How to reorder a result when using TOP clause? - sql

I used this code to select last 5 rows from table:
SELECT TOP(5) * FROM tbl_reg ORDER BY Id DESC
But I want to reorder this result ( the last five rows returned ) By Id ASC
How can I do this?

Use a subquery:
select t.*
from (SELECT TOP(5) * FROM tbl_reg ORDER BY Id DESC) t
order by id ASC;

Related

How to group and pick only certain values based on a field using select query SQL

I have a table as follow
ID
ORDERNO
1
123
1
123
2
456
2
456
During every select query done via application using JDBC, only the grouped records based on ORDERNO should be picked.
That means, for example, during first select query only details related to ID = 1, but we cannot specify the ID number in where clause because we do not know how many number of IDs will be there in future. So the query should yield only one set of records; application will delete those records after picking, hence next select query will result in picking other set of records. How to achieve it?
You can use TOP WITH TIES for this
SELECT TOP (1) WITH TIES
t.ID,
t.ORDERNO
FROM YourTable t
ORDER BY
t.ID;
If you want to select and delete at the same time you could delete using an OUTPUT clause
WITH cte AS (
SELECT TOP (1) WITH TIES
t.ID,
t.ORDERNO
FROM YourTable t
ORDER BY
t.ID
)
DELETE cte
OUTPUT deleted.*;
As one option you could select on the MIN(ID) like:
SELECT *
FROM yourtable
WHERE ID = (SELECT MIN(ID) FROM yourtable);
You could also use window functions to do this:
SELECT ID, ORDERNO
FROM
(
SELECT ID, ORDERNO
DENSE_RANK() OVER (ORDER BY ID ASC) AS dr
FROM yourtable
)dt
WHERE dr = 1;
order your rows and select top n number of rows that you want :
select top (1) with ties ID, ORDERNO
from tablename
order by ID asc

Opposite of TOP in SQL Server

I need to retrieve the last few entries from a table. I can retrieve them using:
SELECT TOP n *
FROM table
ORDER BY id DESC
That I looked everywhere and that's the only answer I could find, But that way I get them in reverse order. I need them in the same order as they are in the table because it's for a messaging interface.
Use a derived table:
select id, ...
from
(
select top n id, ...
from t
order by id desc
) dt
order by id
I suggest you to use a ROW_NUMBER() like this:
SELECT *
FROM (
SELECT
*, ROW_NUMBER() OVER (ORDER BY id DESC) AS RowNo
FROM
yourTable
) AS t
WHERE
(RowNO < #n)
ORDER BY
id

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?
You can use the first query to get the matching ids, and use them as part of an IN clause:
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
You could simply use a sub-query. If you apply a TOP clause the nested ORDER BY is allowed:
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. It
cannot include a COMPUTE or FOR BROWSE clause, and may only include an
ORDER BY clause when a TOP clause is also specified.
Subquery Fundamentals
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
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
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 ;

Find n largest values in a column

I am trying to find the n largest numbers in a particular column in SQL Server.
We can find the largest value in a column and the 2nd largest value easily.
But how do I find say, 5 largest values in a column ?
You tagged this both for MySQL and SQL Server. In SQL Server you can use TOP:
SELECT TOP 5 yourColumn
FROM yourTable
ORDER BY someColumn DESC;
TOP limits the number of rows returned. To get the data with the largest/smallest values you will want to include an ORDER BY.
In MySQL you will use LIMIT
Another way to do this in SQL Server is using row_number():
select id
from
(
select id, row_number() over(order by id desc) rn
from yourtable
) x
where rn <= 5
See SQL Fiddle With Demo
In MySql you can use [LIMIT {[offset,] row_count }] to do this like so:
...
ORDER BY SomeField DESC
LIMIT #n;
For SQL Server you can use the TOP(n) to get the top n:
SELECT TOP(#n) SomeFieldName
FROM TABLE
ORDER BY SomeField DESC
For example:
SELECT TOP 5 items_sold
FROM tbl_PRODUCT
ORDER BY items_sold dESC
Update: If you have another table families with a foreign key family_ID to products table, and you want to find all products with the top n family id's. Then you can dot this:
SELECT *
FROM Products WHERE family_ID IN
(
SELECT TOP 5 family_ID
FROM families
ORDER BY family_ID DESC
)
Update 2: The topmost product in each family:
;WITH cte
AS
(
SELECT *,
ROW_NUMBER() OVER(PARTITION BY family_ID ORDER BY items_sold DESC) row_num
FROM #Products
)
SELECT * FROM cte
where row_num = 1
Order by family_ID
Here is alive demo
sql server
select min(val)
from your_table
where val in (select top 5 val from your_table order by val desc)
mysql
select min(val)
from your_table
where val in (select val from your_table order by val desc limit 5)

SQL Server reverse order after using desc

I want to reverse the order in SQL Server of results after using desc. For example:
SELECT TOP 3 * FROM table ORDER BY id DESC
returns results:
505
504
503
But then I want to flip the results to look like this:
503
504
505
I tried
SELECT * FROM (SELECT TOP 3 * FROM table ORDER BY id DESC) ORDER BY id ASC
But that did not work. How can I fix it?
That should work as long as you alias the subquery.
SELECT q.*
FROM (SELECT TOP 3 *
FROM table
ORDER BY id DESC) q
ORDER BY q.id ASC
I think you forgot the subselect alias
SELECT *
FROM (
SELECT TOP 3 *
FROM table
ORDER BY id DESC
) s
ORDER BY id ASC
SELECT * FROM (SELECT TOP 3 * FROM table ORDER BY id DESC) As AliasName ORDER BY id ASC
;WITH cte
AS
(
SELECT *, ROW_NUMBER() OVER(ORDER BY id DESC) rank
FROM table
)
SELECT *
FROM cte
WHERE rank <= 3
ORDER BY id ASC
SELECT * FROM (SELECT TOP 3 * FROM table ORDER BY id DESC) AS r ORDER BY r.id ASC
I figured it out. I needed to make a temporary table and have a name using AS.
SELECT *
FROM (
SELECT *
FROM table
ORDER BY ID DESC
) TMP
ORDER BY TMP.ID ASC