SQL query to find the top rows in SQL Server - sql-server

In SQL Server, I am trying to get the top 5 salaries.
I have salaries like
5000
5000
4500
4500
3000
2000
1000
500
400
and I'd like to get
5000
5000
4500
4500
3000
2000
1000

SELECT TOP 5 salary FROM your_table
ORDER BY salary DESC

If you want to get the top 5 distinct salaries (no matter how many times the same amount might show up), you need to use the DENSE_RANK() ranking function and a CTE to achieve this:
DECLARE #salaries TABLE (salary DECIMAL(18,4))
INSERT INTO #salaries VALUES(5000)
INSERT INTO #salaries VALUES(5000)
INSERT INTO #salaries VALUES(4500)
INSERT INTO #salaries VALUES(4500)
INSERT INTO #salaries VALUES(3000)
INSERT INTO #salaries VALUES(2000)
INSERT INTO #salaries VALUES(1000)
INSERT INTO #salaries VALUES(500)
INSERT INTO #salaries VALUES(400)
;WITH SalariesRanked AS
(
SELECT
Salary,
SalaryNumber = DENSE_RANK() OVER(ORDER BY Salary DESC)
FROM
#salaries
)
SELECT salary
FROM SalariesRanked
WHERE SalaryNumber <= 5
This results in an output like this:
salary
5000.0000
5000.0000
4500.0000
4500.0000
3000.0000
2000.0000
1000.0000

select salary
from
(
select salary,
dense_rank() over(order by salary desc) as rn
from YourTable
) as T
where rn <= 5
Try on SE-Data

Have a look at using TOP (Transact-SQL)

SELECT TOP 5 Salary
FROM [Table]
GROUP BY Salary
ORDER BY Salary DESC
You need to group the query to avoid the duplicated salaries.

Related

Select next highest data element in a series of values

I have a table that has a list of individuals responsible for monetary thresholds. Table Thresholds looks like:
John Smith 5000.00
Carla Smith 3000.00
Anna Smith 1000.00
I am trying to craft a select statement where I can return the name of the individual for the next highest threshold. So I have an order that is for 1500.00. I want to return Carla's name since the value is above Anna's, but I don't want to see John as an option.
What would you recommend?
Declare #YourTable table (Name varchar(50),SomeValue int)
Insert Into #YourTable values
('John Smith',5000),
('Carla Smith',3000),
('Anna Smith',1000)
;with cte as (
Select *,RN=Row_Number() over (Order by SomeValue)
From #YourTable
Where SomeValue >= 1500
)
Select * from cte where RN=1
Returns
Name SomeValue RN
Carla Smith 3000 1
Or has #James suggested (in case of a tie)
;with cte as (
Select *,Rnk=Dense_Rank() over (Order by SomeValue)
From #YourTable
Where SomeValue >= 1500
)
Select * from cte where Rnk=1
Using TOP:
Select top 1 * from table Where value >= 1500 order by value

SQL Server query should return max value records

I have table like this:
id_Seq_No emp_name Current_Property_value
-----------------------------------------------
1 John 100
2 Peter 200
3 Pollard 50
4 John 500
I want the max record value of particular employee.
For example, John has 2 records seq_no 1, 4. I want 4th seq_no Current_Property_Value in single query.
Select
max(id_Seq_No)
from
t1
where
emp_name = 'John'
To get the Current_Property_value, just order the results by id_Seq_No and get the first one:
SELECT
TOP 1 Current_Property_value
FROM
table
WHERE
emp_name = 'John'
ORDER BY
id_Seq_No DESC
this will give highest for all tied employees
select top 1 with ties
id_Seq_No,emp_name,Current_Property_value
from
table
order by
row_number() over (partition by emp_name order by Current_Property_value desc)
You can use ROW_NUMBER with CTE.
Query
;WITH CTE AS(
SELECT rn = ROW_NUMBER() OVER(
PARTITION BY emp_name
ORDER BY id_Seq_No DESC
), *
FROM your_table_name
WHERE emp_name = 'John'
)
SELECT * FROM CTE
WHERE rn = 1;

How to give numbers to the result after executing the query in sql server?

I have a table with some 100 records and Total is the one of the colum in the table.I am arranging the rows in the table in the DESC order with the following query.
Select Name,Total from tbl_one group by Toal DESC
Now my requirment is after getting this result I need to give number to each record starting from first. like
John 500 1
Sam 490 2
David 480 3 and till 100
Please suggest me the best way of doing this. I am using SQL Server 2008 R2.
Your query will not work. But this is the method used to select an enumerating column:
SELECT Name, Total, ROW_NUMBER() OVER(ORDER BY Total DESC) AS RN
FROM tbl_one
ORDER BY RN ASC
You can do this with ROW_NUMBER window function:
select Name, Total, Row_Number() Over(Order By Total DESC) as RowIndex
from tbl_one
order by RowIndex
PS: in Sql Server you call it ROW not RECORD.
You could use the row_number window function:
SELECT Name, Total, ROW_NUMBNER() OVER (ORDER BY Total)
FROM tbl_one
ORDER BY Toal DESC
SELECT
Name,
Total,
Index = ROW_NUMBER() OVER(PARTITION BY [Total] ORDER BY [Total])
FROM tbl_one
To retain the grouping
DECLARE #startnum INT=400
DECLARE #endnum INT=1400
;
WITH gen AS (
SELECT #startnum AS num
UNION ALL
SELECT num+10 FROM gen WHERE num + 1<=#endnum
)
SELECT 'Some name',num,ROW_NUMBER()OVER( ORDER BY num DESC) FROM gen order by num desc
option (maxrecursion 10000)

In SQL Server how can I fetch all rows with a date greater than some set date or at least 20 rows

I'm looking for a way to fetch at least 20 rows, regardless of the date or all rows with a date greater than a set date (whichever of the 2 fetches the most rows).
For example:
SELECT *
FROM table1
WHERE the_date >= '2014-11-01'
ORDER BY the_date DESC
will give me what I want, but if this returns less than 20 rows then I want to keep going before that date until I get 20 (or until there are no more rows - whichever comes first).
I could just select all and take the ones I need programatically, but I'm trying to avoid that as that would be a major change to the actual code in many places.
Can this be done?
Note: I am using SQL Server 2008.
Here's an approach:
select *
from
(
select row_number() over (order by the_date desc) num, t.*
from table1 t
) i
where i.the_date >= '2014-11-01'
or i.num < 21
Very strange requirement but something like this should work.
DECLARE #Date date = '2014-11-01';
with MyResults as
(
SELECT *, 1 as RowNum
FROM table1
WHERE (the_date >= #Date )
UNION ALL
SELECT top 10 *, ROW_NUMBER() over(order by the_date desc)
FROM table1
order by the_date desc
)
Select *
from MyResults
where RowNum <= 20
The right answer was almost there, but the user has removed it, so here it is again:
SELECT *
FROM table1
WHERE the_date >= '2014-11-01'
union
SELECT top 20 *
FROM table1
ORDER BY the_date desc
The removed answer had union all
This answer has a problem with duplicate dates , but with the data I have that is not an issue

How to get row between an intervalle of row number?

Is it possible in sql server to get the lines from row 10 to row 20 for example ?
I mean, I'm getting more than 1800 rows by querying the database and then i would like to display them 10 by 10.
Use a CTE to add a column that represents row number of each row and then filter by that column.
;WITH MyCTE AS
(
SELECT *,
ROW_NUMBER() OVER(ORDER BY ID) RowNum
FROM Table
)
SELECT *
FROM MyCTE
WHERE RowNum BETWEEN 10 AND 20
Or in SQL 2012+, use OFFSET\FETCH
....
ORDER BY ...
OFFSET 10 ROWS
FETCH NEXT 10 ROWS;
See http://msdn.microsoft.com/en-us/library/ms188385%28v=SQL.110%29.aspx
Example:
WITH ResultSetWithRowNumber AS
(
SELECT ROW_NUMBER() OVER(ORDER BY MyField1) AS RowNumber, MyField1, MyField2
FROM MyTable
WHERE MyField2 = SomeValue
)
SELECT RowNumber, MyField1, MyField2
FROM ResultSetWithRowNumber
WHERE RowNumber BETWEEN 10 AND 20
MSDN

Resources