I am trying to order the last 5 entries to the database and select them to show but I am having no luck, http://sqlfiddle.com/#!6/8bd8a/2 as you can see I replicated the code I have and you can see it is ordering by [id] how can I change the SQL code so that the 9 in the ID column starts at the bottom instead of at the top.. so that it can be like
5
6
7
8
9
One way is to wrap your original statement in an outer statement that sorts ascending:
select * from (
select top 5 *
from yourtable
order by id desc
) a
order by id asc
Sample SQL Fiddle
Or you could use a common table expression (cte):
WITH cte AS (
SELECT TOP (5) *
FROM YourTable ORDER BY id DESC
)
SELECT * FROM cte ORDER BY id ASC
The following query should provide you the expected result:
SELECT *
FROM (SELECT TOP 5 T2.*
FROM yourtable T2
ORDER BY T2.id DESC) T
ORDER BY T.id
Hope this will help you.
Related
I need to have one query for to select all records of KitchenBlinkSound='Y' plus top 1 of KitchenBlinkSound='N', here is my table structure.
And my requested result will be OrderNo 225,226,227. Basically it contains all KitchenBlinkSound='Y' records plus top 1 of KitchenBlinkSound='N' record.
SELECT * FROM TABLE WHERE KitchenBlinkSound='Y'
UNION ALL
SELECT TOP 1 * FROM TABLE WHERE KitchenBlinkSound='N'
ORDER BY ORDERNO
UPDATE
SELECT TOP 3 * FROM
(
SELECT * FROM #TABLE1 WHERE KitchenBlinkSound='Y'
UNION ALL
SELECT ORDERNO,KITCHENSTATUS,KitchenBlinkSound FROM
(
SELECT *,
ROW_NUMBER() OVER(PARTITION BY KitchenBlinkSound ORDER BY ORDERNO ASC) RNO
FROM #TABLE1 WHERE KitchenBlinkSound='N'
)TAB
WHERE TAB.RNO=1
)MAIN
As sub-queries doesn't allow ORDER BY, ROW_NUMBER() is added in order to make sure that you are selecting the TOP 1 ORDERNO in ascending order. If you want to take in descending order change ASC to DESC.
Select * from [your table name] where KitchenBlickSound = 'Y'
UNION
Select TOP 1 * from [your table name] where KitchenBlickSound = 'N'
I read one SQL statement like this:
select top 1 id from (
select top 1 id from sysobjects where xtype='u' order by id
) sq order by id desc
I don't understand what 'sq' in the last line stands for. Thanks for any helpful answers.s
It is just an Alias for the subquery, it could also be written as: AS sq ...
select top 1 id from (
select top 1 id from sysobjects where xtype='u' order by id
) AS sq order by id desc
Here is an example of using the sq alias:
select top 1 sq.id from (
select top 1 id from sysobjects where xtype='u' order by id
) sq order by id desc
You can have as many columns as you want in the subselect but there must be one called id. Here I am also aliasing the column names (since they are just constants in this case)
select top 1 sq.id from (
select top 1 id, 'A' Col1, 'B' Col2, 7 as Col3
from sysobjects where xtype='u' order by id
) sq order by id desc
How can I get the n-th row of a TSQL query results?
Let's say, I want to get the 2nd row of this SELECT:
SELECT * FROM table
ORDER BY 2 ASC
What version of SQL Server are you targeting? If 2005 or greater, you can use ROW_NUMBER to generate a row number and select using that number. http://msdn.microsoft.com/en-us/library/ms186734.aspx
WITH orderedtable AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY <your order here>) AS 'RowNumber'
FROM table
)
SELECT *
FROM orderedtable
WHERE RowNumber = 2;
You can use a trick combining TOP with ORDER BY ASC/DESC to achieve an effect similar to MySQL's LIMIT:
SELECT TOP 2 * INTO #temptable FROM table
ORDER BY 2 ASC
SELECT TOP 1 * FROM #temptable
ORDER BY 2 DESC
or without temptable, but nested statements:
SELECT TOP 1 * FROM
(
SELECT TOP 2 * FROM table
ORDER BY 2 ASC
) sub
ORDER BY 2 DESC
The first time you select all rows up to the one you want to actually have, and in the second query you select only the first of the remaining when ordering them reversely, which is exactly the one you want.
Source: http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=850&lngWId=5
One way;
;with T(rownumber, col1, colN) as (
select
row_number() over (order by ACOLUMN) as rownumber,
col1,
colN
from
atable
)
select * from T where rownumber = 2
How to select top 2 , bottom 2 and 6 random (not in Top 2 and Bottom 2) records of the table using one SQL select query?
In MS SQL 2005/2008:
with cte
as
(
select
row_number() over (order by name) RowNumber,
row_number() over (order by newid()) RandomOrder,
count(*) over() Total,
*
from sys.tables
)
select *
from cte
where RowNumber <= 2 or Total - RowNumber + 1 <= 2
union all
select *
from
(
select top 6 *
from cte
where RowNumber > 2 and Total - RowNumber > 2
order by RandomOrder
) tt
Replace sys.tables with your table name and alter order by name to specify order condition for top 2 and bottom 2.
Perhaps not a single select statment, but it can be executed in one call:
/* Top 2 - change order by to get the 'proper' top 2 */
SELECT * from table ORDER BY id DESC LIMIT 2
UNION ALL
/* Random 6.. You may want to add a WHERE and random data to get the random 6 */
/* Old Statement before edit - SELECT * from table LIMIT 6 */
SELECT * from table t
LEFT JOIN (SELECT * from table ORDER BY id DESC LIMIT 2) AS top ON top.id = t.id
LEFT JOIN (SELECT * from table ORDER BY id DESC LIMIT 2) AS bottom ON bottom.id = t.id
WHERE ISNULL(top.id ) AND ISNULL(bottom.id)
ORDER BY RANDOM()
LIMIT 6
UNION ALL
/* Bottom 2 - change order by to get the 'proper' bottom 2 */
SELECT * from table ORDER BY id ASC LIMIT 2
Something along those lines. Basically the UNION All is the trick.
Assuming the "order" is by the id column:
select * from (select id, id from my_table order by id limit 2) t1
union
select * from (select id, id from my_table where id not in (
select * from (select id from my_table order by id asc limit 2) t22
union
select * from (select id from my_table order by id desc limit 2 ) t23)
order by rand()
limit 6) t2
union
select * from (select id, id from my_table order by id desc limit 2) t3
EDIT: Fixed syntax and tested query - it works
I'm using SQL Server 2005 and I'm trying to achieve something like this:
I want to get the first x rows and the last x rows in the same select statement.
SELECT TOP(5) BOTTOM(5)
Of course BOTTOM does not exist, so I need another solution. I believe there is an easy and elegant solution that I'm not getting. Doing the select again with GROUP BY DESC is not an option.
Using a union is the only thing I can think of to accomplish this
select * from (select top(5) * from logins order by USERNAME ASC) a
union
select * from (select top(5) * from logins order by USERNAME DESC) b
Check the link
SQL SERVER – How to Retrieve TOP and BOTTOM Rows Together using T-SQL
Did you try to using rownumber?
SELECT *
FROM
(SELECT *, ROW_NUMBER() OVER (Order BY columnName) as TopFive
,ROW_NUMBER() OVER (Order BY columnName Desc) as BottomFive
FROM Table
)
WHERE TopFive <=5 or BottomFive <=5
http://www.sqlservercurry.com/2009/02/select-top-n-and-bottom-n-rows-using.html
I think you've two main options:
SELECT TOP 5 ...
FROM ...
ORDER BY ... ASC
UNION
SELECT TOP 5 ...
FROM ...
ORDER BY ... DESC
Or, if you know how many items there are in the table:
SELECT ...
FROM (
SELECT ..., ROW_NUMBER() OVER (ORDER BY ... ASC) AS intRow
FROM ...
) AS T
WHERE intRow BETWEEN 1 AND 5 OR intRow BETWEEN #Number - 5 AND #Number
Is it an option for you to use a union?
E.g.
select top 5 ... order by {specify columns asc}
union
select top 5 ... order by {specify columns desc}
i guess you have to do it using subquery only
select * from table where id in (
(SELECT id ORDER BY columnName LIMIT 5) OR
(SELECT id ORDER BY columnName DESC LIMIT 5)
)
select * from table where id in (
(SELECT TOP(5) id ORDER BY columnName) OR
(SELECT TOP(5) id ORDER BY columnName DESC)
)
EDITED
select * from table where id in (
(SELECT TOP 5 id ORDER BY columnName) OR
(SELECT TOP 5 id ORDER BY columnName DESC)
)
No real difference between this and the union that I'm aware of, but technically it is a single query.
select t.*
from table t
where t.id in (select top 5 t2.id from table t2 order by MyColumn)
or
t.id in (select top 5 t2.id from table t2 order by MyColumn desc);
SELECT *
FROM (
SELECT x, rank() over (order by x asc) as rown
FROM table
) temp
where temp.rown = 1
or temp.rown = (select count(x) from table)
Then you are out - doing the select again IS the only option, unless you want to pull in the complete result set and then throwing away everything in between.
ANY sql I cna think of is the same way - for the bottom you need to know first either how many items you have (materialize everything or use count(*)) or a reverse sort order.
Sorry if that does not suit you, but at the end.... reality does not care, and I do not see any other way to do that.
I had to do this recently for a very large stored procedure; if your query is quite large, and you want to minimize the amount of queries you could declare a #tempTable, insert into that #tempTable then query from that #tempTable,
DECLARE #tempTable TABLE ( columns.. )
INSERT INTO #tempTable
VALUES ( SELECT.. your query here ..)
SELECT TOP(5) columns FROM #tempTable ORDER BY column ASC -- returns first to last
SELECT TOP(5) columns FROM #tempTable ORDER BY column DESC -- returns last to first