Solved

How to order Highest and lowest value rows alternatively in SQL Server ?

Posted on 2016-11-18
4
71 Views
Last Modified: 2016-11-18
Sample data-

CREATE TABLE #emp_records
(
 Id INT,
 Name VARCHAR(80),
 Salary NUMERIC(8, 2)
)
GO
 
INSERT INTO #emp_records
(Id, Name, Salary)
VALUES(1, 'A', 7000),
(2, 'B', 30000),
(3, 'C', 6000),
(4, 'D', 10000),
(5, 'E', 800),
(6, 'F', 500)

Desired Output :-

Id      Name      Salary
2      B      30000.00
6      F      500.00
4      D      10000.00
5      E      800.00
1      A      7000.00
3      C      6000.00
0
Comment
Question by:Mayank Tripathi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 28

Expert Comment

by:Pawan Kumar
ID: 41892727
Do you always have even number in this case ? or we can have odd number also ?
0
 

Author Comment

by:Mayank Tripathi
ID: 41892728
Thanks Pawan, by the way the rows are not fixed.
0
 
LVL 28

Accepted Solution

by:
Pawan Kumar earned 500 total points
ID: 41892731
try..

---

DECLARE @Count INT = 0
SELECT @Count = COUNT(1) FROM emp_records
DECLARE @limit INT = CEILING(@Count / 2.0)

;WITH CTE AS
(
	SELECT * FROM
	(
		SELECT * , ROW_NUMBER() OVER(ORDER BY Salary DESC) rnk FROM emp_records
	)B1 
	WHERE rnk <= @limit
)
,CTE1 AS 
(
	SELECT * FROM
	(
		SELECT *, ROW_NUMBER() OVER(ORDER BY Salary ASC) rnk FROM emp_records
	)B2
	WHERE rnk <= @limit - (@Count % 2.0) 
)
SELECT * FROM CTE c
UNION ALL
SELECT * FROM CTE1
ORDER BY rnk ASC, Salary DESC

Open in new window


Hope it helps !
0
 

Author Closing Comment

by:Mayank Tripathi
ID: 41892793
Thanks.
0

Featured Post

[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Viewers will learn how the fundamental information of how to create a table.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question