SQL Server need top 1 record for one column and all other records - sql

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'

Related

Using UNION withing ORDER in SQL Server

I want to retrieve latest records of two tables using UNION, it returns data, but not latest records, even with ORDER BY. It's my query:
SELECT TOP(1) OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName
FROM TheaterNews
UNION
SELECT TOP(3) OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName
FROM MoviesNews
ORDER BY 3 DESC
This is query's output:
But the latest record of TheaterNews is newer:
SELECT OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName
FROM TheaterNews
ORDER BY NewsCreationDate DESC
How can I fix this? even with another method.
The order by applies to the entire result of the union, not the separate queries, so the top is applied before the result is sorted.
Use subqueries to order the separate results:
SELECT * FROM (
SELECT TOP(1) OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName
FROM TheaterNews
ORDER BY 3 DESC
) x
UNION
SELECT * FROM (
SELECT TOP(3) OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName
FROM MoviesNews
ORDER BY 3 DESC
) y
Because top clause is getting executed before order by clause. try this
Select * from (SELECT TOP(1) OwnerID,NewsTitle,NewsCreationDate,
NewsEnglishName
FROM TheaterNews ORDER BY 3 DESC) as tn
UNION
Select * From (SELECT TOP(3)
OwnerID,NewsTitle,NewsCreationDate,NewsEnglishName
FROM MoviesNews ORDER BY 3 DESC) as mn
ORDER BY 3 DESC
The outer order by will order the union result
This should work in your instance. Might be a rough solution but you will get your answers. you can replace the #tables with #tables.
SELECT TOP(1)
OwnerID,
NewsTitle,
NewsCreationDate,
NewsEnglishName
into
#Table1
FROM
TheaterNews
ORDER BY 3 DESC
SELECT TOP(3)
OwnerID,
NewsTitle,
NewsCreationDate,
NewsEnglishName
into
#Table2
FROM
MoviesNews
ORDER BY 3 DESC
select * from #Table1
union
select * from #Table2
drop table #Table1
drop table #Table2
Try this:
Select * From ( SELECT TOP(1) OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName
FROM TheaterNews ORDER BY NewsCreationDate DESC) as tempA
UNION
Select * From ( SELECT TOP(3) OwnerID,NewsTitle,NewsCreationDate,NewsTitle,NewsEnglishName
FROM MoviesNews ORDER BY NewsCreationDate DESC) as tempB

How can I get the n-th row in the Query results?

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

Sql Select top 2 , bottom 2 and 6 random records

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

Select top and bottom rows

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

SQL Server Top 1

In Microsoft SQL Server 2005 or above, I would like to get the first row, and if there is no matching row, then return a row with default values.
SELECT TOP 1 ID,Name
FROM TableName
UNION ALL
SELECT 0,''
ORDER BY ID DESC
This works, except that it returns two rows if there is data in the table, and 1 row if not.
I'd like it to always return 1 row.
I think it has something to do with EXISTS, but I'm not sure.
It would be something like:
SELECT TOP 1 * FROM Contact
WHERE EXISTS(select * from contact)
But if not EXISTS, then SELECT 0,''
What happens when the table is very full and you might want to specify which row of your top 1 to get, such as the first name? OMG Ponies' query will return the wrong answer in that case if you just change the ORDER BY clause. His query also costs about 8% more CPU than this modification (though it has equal reads)
SELECT TOP 1 *
FROM (
SELECT TOP 1 ID,Name
FROM TableName
ORDER BY Name
UNION ALL
SELECT 0,''
) X
ORDER BY ID DESC
The difference is that the inner query has a TOP 1 also, and which TOP 1 can be specified there (as shown).
Just for fun, this is another way to do it which performs very closely to the above query (-15ms to +30ms). While it's more complicated than necessary for such a simple query, it demonstrates a technique that I don't see other SQL folks using very often.
SELECT
ID = Coalesce(T.ID, 0),
Name = Coalesce(T.Name, '')
FROM
(SELECT 1) X (Num)
LEFT JOIN (
SELECT TOP 1 ID, Name
FROM TableName
ORDER BY ID DESC
) T ON 1 = 1 -- effective cross join but does not limit rows in the first table
Use:
SELECT TOP 1
x.id,
x.name
FROM (SELECT t.id,
t.name
FROM TABLENAME t
UNION ALL
SELECT 0,
'') x
ORDER BY id DESC
Using a CTE equivalent:
WITH query AS (
SELECT t.id,
t.name
FROM TABLENAME t
UNION ALL
SELECT 0,
'')
SELECT TOP 1
x.id,
x.name
FROM query x
ORDER BY x.id DESC
CREATE TABLE #sample(id INT, data VARCHAR(10))
SELECT TOP 1 id, data INTO #temp FROM #sample
IF ##ROWCOUNT = 0 INSERT INTO #temp VALUES (null, null)
SELECT * FROM #temp
put the top oustide of the UNION query
SELECT TOP 1 * FROM(
SELECT ID,Name
FROM TableName
UNION ALL
SELECT 0,''
) z
ORDER BY ID DESC
IF EXISTS ( SELECT TOP 1 ID, Name FROM TableName )
BEGIN
SELECT TOP 1 ID, Name FROM TableName
END
ELSE
BEGIN
--exists returned no rows
--send a default row
SELECT 0, ''
END