Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I have one query which is : select top 5 Salary from FEmployee E where E.Designation ='Manager'

this query returns me 4 records as there are only 4 records which match the criteria.

Now what i want is when it returns 4 records and i select top 5 records then it should return me 5th record as NULL

Please help me in achieving this. I am really stuck up.

Thanks.

Krunal
Posted
Comments
[no name] 4-Sep-14 2:27am    
why it's necessary like this?
If you want to add blank row then add it front end in your dataTable
Thanks7872 4-Sep-14 2:28am    
What you mean by this line : when it returns 4 records and i select top 5 records then it should return me 5th record as NULL?

Something like

SQL
Select top 5 salary from
(
select top 5  salary from Employee where designation = 'Manager'
union all
select null from employee

) AS ABC


should do what you want it to.
 
Share this answer
 
v2
Comments
Gihan Liyanage 4-Sep-14 3:19am    
GREAT SOLUTION Max !,I have edited bit by adding alias, because otherwise it might had syntax error in query,
_Maxxx_ 4-Sep-14 6:15am    
Thanks - I think I missed that when I copied it over from SSMS - it was 5-past going-home time so I was i a rush :)
Gihan Liyanage 4-Sep-14 6:18am    
Ohh , yes I thought it was a mistake..
A more elegant solution could be like

SQL
DECLARE @TBL TABLE
(
	EMPID INT,
	DESIGNATION VARCHAR(20),
	SALARY FLOAT
)

INSERT INTO @TBL (EMPID, DESIGNATION, SALARY)
SELECT 102, 'MANAGER', 55000
UNION ALL
SELECT 234, 'MANAGER', 45000
UNION ALL
SELECT 345, 'MANAGER', 35000
UNION ALL
SELECT 446, 'MANAGER', 25000

SELECT T.SALARY
FROM 
	(select 1 as ROWID
	UNION ALL
	select 2
	UNION ALL
	select 3 
	UNION ALL
	select 4 
	UNION ALL
	select 5 
	) A LEFT OUTER JOIN 
	(
	SELECT TOP 5 ROW_NUMBER() OVER (ORDER BY EMPID) AS ROWID, *
	FROM @TBL T
	) T ON T.ROWID = A.ROWID
 
Share this answer
 
Comments
_Maxxx_ 4-Sep-14 6:21am    
wow - not sure about elegant, but certainly more complex! Surely, if you decided you wanted 50 rows instead of 5, this is going to prove a little harder to maintain?
_Asif_ 4-Sep-14 7:39am    
Well it could manage additional NULL rows if Top 5 returns < 4 rows as well and that's the reason for being elegant :) Well the interim table was used just to explain the concept, a more appropriate solution could be to use a proper table instead of interim table for the same purpose.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900