I have a Story table, and I need the following query:
- first 6 rows sorted by distance (I calculate it)
- next rows are sorted by TIME property descending
declare #profileID int
set #profileID = 6
declare #longitude float
set #longitude = 17.6009169090776
declare #latitude float
set #latitude = 46.9548404806283
SELECT
first.*
FROM
(
SELECT top 6
[dbo].[Story].*,
SQRT( POWER(#Longitude - [dbo].[Story].[Longitude], 2) + POWER(#Latitude - [dbo].[Story].[Latitude], 2)) as [DistanceFromUser]
FROM
[dbo].[Follow]
LEFT JOIN
[dbo].[Story]
ON
[dbo].[Follow].[Followed] = [dbo].[Story].[ProfileID]
WHERE
[dbo].[Follow].[Follower] = #ProfileID and
[dbo].[Story].IsDraft = 0
ORDER BY
[DistanceFromUser] asc
) first
UNION ALL
SELECT
last.*
FROM
(
SELECT TOP 100 PERCENT
[dbo].[Story].*,
SQRT( POWER(#Longitude - [dbo].[Story].[Longitude], 2) + POWER(#Latitude - [dbo].[Story].[Latitude], 2)) as [DistanceFromUser]
FROM
[dbo].[Follow]
LEFT JOIN
[dbo].[Story]
ON
[dbo].[Follow].[Followed] = [dbo].[Story].[ProfileID]
WHERE
[dbo].[Follow].[Follower] = #ProfileID and
[dbo].[Story].IsDraft = 0
**ORDER BY
Time desc**
) last
My problem is the second query. It not sorts the records after the 6'th row descending by the TIME property, it sorts as ascending.
thnx
Try This
SELECT
first.*
FROM
(
SELECT top 6
[dbo].[Story].*,
SQRT( POWER(#Longitude - [dbo].[Story].[Longitude], 2) + POWER(#Latitude - [dbo].[Story].[Latitude], 2)) as [DistanceFromUser]
,1 as ord
FROM
[dbo].[Follow]
LEFT JOIN
[dbo].[Story]
ON
[dbo].[Follow].[Followed] = [dbo].[Story].[ProfileID]
WHERE
[dbo].[Follow].[Follower] = #ProfileID and
[dbo].[Story].IsDraft = 0
ORDER BY
[DistanceFromUser] asc
) first
UNION ALL
SELECT
last.*
FROM
(
SELECT TOP 100 PERCENT
[dbo].[Story].*,
SQRT( POWER(#Longitude - [dbo].[Story].[Longitude], 2) + POWER(#Latitude - [dbo].[Story].[Latitude], 2)) as [DistanceFromUser]
,row_number() over(order by Time desc) as ord
FROM
[dbo].[Follow]
LEFT JOIN
[dbo].[Story]
ON
[dbo].[Follow].[Followed] = [dbo].[Story].[ProfileID]
WHERE
[dbo].[Follow].[Follower] = #ProfileID and
[dbo].[Story].IsDraft = 0
**ORDER BY
Time desc**
) last
My try (example)
declare #ta as table
(
id int
,na varchar(100)
,sal numeric(18,2)
)
insert into #ta( id,na,sal) values (1,'aa',10)
insert into #ta( id,na,sal) values (3,'bb',100)
insert into #ta( id,na,sal) values (2,'c',5)
insert into #ta( id,na,sal) values (4,'dd',50)
select * from
(select top 2 * , 1 as ord from #ta order by id) as f
union all
select * from (select top 100 percent * , row_number() over(order by sal desc) ord from #ta order by sal desc
) as tt
If you want the result set ordered in a particular way, then the outermost SELECT needs an ORDER BY.
You can control the ordering by including multiple keys in the outer ORDER BY. If I'm reading the query correctly, the only difference is the order by, so put the logic for the queries in a CTE:
WITH sf as (
SELECT s.*,
SQRT( POWER(#Longitude - s.[Longitude], 2) + POWER(#Latitude - s.[Latitude], 2)) as [DistanceFromUser]
FROM [dbo].[Follow] f LEFT JOIN
[dbo].[Story] s
ON f.[Followed] = s.[ProfileID]
WHERE f.[Follower] = #ProfileID and
s.IsDraft = 0
)
SELECT sf.*
FROM ((SELECT TOP (6) sf.*, 1 as ord
FROM sf
ORDER BY [DistanceFromUser] ASC
) UNION ALL
(SELECT TOP (6) sf.*, 2 as ord
FROM sf
ORDER BY Time DESC
)
) sf
ORDER BY ord,
(CASE WHEN ord = 1 THEN DistanceFromUser END) ASC,
(CASE WHEN ord = 2 THEN Time END) DESC;
You can also do this with window functions:
WITH sf as (
SELECT s.*,
SQRT( POWER(#Longitude - s.[Longitude], 2) + POWER(#Latitude - s.[Latitude], 2)) as [DistanceFromUser]
FROM [dbo].[Follow] f LEFT JOIN
[dbo].[Story] s
ON f.[Followed] = s.[ProfileID]
WHERE f.[Follower] = #ProfileID and
s.IsDraft = 0
)
SELECT sf.*
FROM (SELECT sf.*,
ROW_NUMBER() OVER (ORDER BY DistanceFromUser) as seqnum_d,
ROW_NUMBER() OVER (ORDER BY Time DESC) as seqnum_t
FROM sf
)
) sf
WHERE seqnum_d <= 6 OR seqnum_t <= 6
ORDER BY ord,
(CASE WHEN seqnum_d <= 6 THEN DistanceFromUser END) ASC,
(CASE WHEN seqnum_t <= 6 THEN Time END) DESC;
Your version could include the same row twice. This version will not duplicate rows that are in the top 6 for both conditions.
So I ended with next solution thnx to everyone
WITH TempTable as
(
SELECT [dbo].[Story].*,
SQRT( POWER(#Longitude - [dbo].[Story].[Longitude], 2) + POWER(#Latitude - [dbo].[Story].[Latitude], 2)) as [DistanceFromUser]
FROM
[dbo].[Follow]
LEFT JOIN
[dbo].[Story]
ON [dbo].[Follow].[Followed] = [dbo].[Story].[ProfileID]
WHERE [dbo].[Follow].[Follower] = #ProfileID and
[dbo].[Story].IsDraft = 0
)
SELECT
first.*
FROM
(
SELECT top 6
*,
1 as ord
FROM
TempTable
ORDER BY
[DistanceFromUser] asc
) first
UNION ALL
SELECT
last.*
FROM
(
SELECT TOP 100 PERCENT
*,
row_number() over(order by Time desc) as ord
FROM
TempTable
ORDER BY
Time desc
) last
Related
Good day, I'm trying to select a data. Please check my query and table first.
I have this query
select * from
(
SELECT * from
(
select distinct TOP 201233 row, b.OutletCode as 'Kode Otlet',
i.Description as 'Area',
c.Nilai,a.Nip, b.Fullname 'Nama Lengkap', f.positioncode as 'Posisi Sebelumnya',
case when a.[status]=0
then j.ApprovedDate else p.ApprovedDate
end as 'Tanggal Upgrade/Demosi Sebelumnya',
d.positioncode as 'Posisi Baru', a.tanggal as 'Tanggal Upgrade/Demosi'
from penilaian_header a
left join Employee b on a.Nip = b.Nip
left join Position f on b.PositionCode = f.PositionCode
left join Position d on a.PositionCode = d.PositionCode
left join arealeader g on g.OutletCode = b.OutletCode
left join outlet h on g.OutletCode = h.OutletCode
left join area i on i.areacode = h.areacode
left join cutoff k on a.periode = k.cutoffcode
left join
(select ROW_NUMBER() OVER(PARTITION BY KodePenilaianH ORDER BY idPenilaiand ASC) AS Row,
Nilai,KodePenilaianH from penilaian_Detail ) c on a.KodePenilaian = c.KodePenilaianH
left join
( SELECT ROW_NUMBER() OVER (PARTITION BY nip ORDER BY ApprovedDate desc) AS rownumber,
ApprovedDate, Nip FROM historyposition ) AS p on a.nip=p.nip and p.rownumber = 2
left join ( SELECT ROW_NUMBER() OVER (PARTITION BY nip ORDER BY ApprovedDate desc) AS rownumber, ApprovedDate, Nip
FROM historyposition ) AS j on a.nip=j.nip and j.rownumber = 1
where a.flag = 1 and h.AreaCode like '%%'
and Periode like '%CO-2016-9-16-15%' and a.nip = '1004863'
--and tanggal <= k.[to] and tanggal >= k.[from]
order by i.Description asc) nilai pivot ( sum(nilai) for row in ([1],[2],[3],[4],[5]) ) piv)A order by Area;
with above query i get this result
and i have this table HistoryPosition
KodeMutasiP OldPosition NewPosition ApprovedBy ApprovedDate Nip KodePenilaian
HP0000514 P007 P007 0802678 2016-09-15 1004863 PE0000787
HP0000513 P007 P007 0802678 2016-04-04 1004863 PE0000130
NULL NULL P007 NULL 2016-04-04 1004863 NULL
NULL NULL P041 NULL 2016-01-20 1004863 NULL
NULL NULL P007 NULL 2015-02-12 1004863 NULL
ok. So what i want to do is set Posisi Sebelumnya and Tanggal Upgrade/Demosi Sebelumnya in the first picture with newposition and Approveddate from the second picture.
But with this condition
if newposition and nip col in the second picture same with the second row then jump to the second, if the second same with the third then jump to the fourth, if the fourth different with the third then choose the third.
I have write the query to choose it here is my query
select * INTO #tMP from historyposition where nip = '1004863' order by approveddate desc
declare #NewPosition varchar(50), #NewPositionLast varchar(50), #ApproveDate datetime, #ApproveDateLast datetime
select top 1 #NewPositionLast = NewPosition, #ApproveDateLast=ApprovedDate from #tmp
WHILE EXISTS (SELECT * FROM #tMP)
BEGIN
select top 1 #NewPosition = NewPosition, #ApproveDate=ApprovedDate from #tmp
if (#NewPosition = #NewPositionLast)
begin
set #NewPositionLast = #NewPosition
set #ApproveDateLast = #ApproveDate
end
else
begin
break
end
delete top(1) #tMP
END
select #NewPositionLast , #ApproveDateLast
drop table #tMP
and i get this result
| P007 | 2016-04-04 00:00:00.000 |
the result is like what i expected.
so my question how to set the Posisi Sebelumnya and Tanggal Upgrade/Demosi Sebelumnya with the result of my last query.
Sorry for my bad english.
here it's my expected result .
I know it's same with the the first picture. But its not right. that because in my first query i choose the second row.
select * from
(
SELECT * from
(
select distinct TOP 201233 row, b.OutletCode as 'Kode Otlet', i.Description as 'Area',
c.Nilai,a.Nip, b.Fullname 'Nama Lengkap',
case when
l.ShortDesc IS NULL then f.ShortDesc else l.ShortDesc
end
as 'PosisiSebelumnya',
-----
z.approveddate,
------
d.ShortDesc as 'Posisi Baru', a.tanggal as 'Tanggal Upgrade/Demosi'
from penilaian_header a
left join Employee b on a.Nip = b.Nip
left join Position f on b.PositionCode = f.PositionCode
left join Position d on a.PositionCode = d.PositionCode
left join position l on a.posisisaatini = l.positioncode
left join arealeader g on g.OutletCode = b.OutletCode
left join outlet h on g.OutletCode = h.OutletCode
left join area i on i.areacode = h.areacode
left join cutoff k on a.periode = k.cutoffcode
left join
(select ROW_NUMBER() OVER(PARTITION BY KodePenilaianH ORDER BY idPenilaiand ASC) AS Row,
Nilai,KodePenilaianH from penilaian_Detail ) c on a.KodePenilaian = c.KodePenilaianH
left join (
select top(1) Nip,NewPosition, ApprovedDate
from (
select Nip,NewPosition,ApprovedDate
, grp = row_number() over(order by ApprovedDate desc) - row_number() over(partition by NewPosition order by ApprovedDate desc)
from HistoryPosition
) t
where grp = 0
order by ApprovedDate
)z on z.Nip = a.Nip
where a.flag = 1
and h.AreaCode like '%%'
and Periode like '%CO-2016-9-16-15%'
and tanggal <= k.[to] and tanggal >= k.[from] order by i.Description asc) nilai
pivot ( sum(nilai) for row in ([1],[2],[3],[4],[5]) ) piv)A order by Area;
i get this.
Your last script retrievs the row with the minimum ApprovedDate. It should be effectively the same as
SELECT ApprovedDate, NewPosition
FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY NewPosition ORDER BY ApprovedDate asc) AS rownumber, ApprovedDate, NewPosition
FROM historyposition
WHERE nip = '1004863') t
WHERE rownumber = 1
Try to use this snippet in your bigger query.
EDIT
Detect first group of NewPosition when historyposition is odered by ApprovedDate desc and take first row witn min ApprovedDate in group.
with HistoryPosition as(
-- sample data
select sKodeMutasiP,OldPosition,NewPosition,ApprovedBy
,cast(ApprovedDate as DATE) ApprovedDate, Nip,KodePenilaian
from (
values
('HP0000514','P007','P007',0802678,'2016-09-15',1004863,'PE0000787')
,('HP0000513','P007','P007',0802678,'2016-04-04',1004863,'PE0000130')
,(NULL,NULL,'P007',NULL,'2016-04-04',1004863,NULL)
,(NULL,NULL,'P041',NULL,'2016-01-20',1004863,NULL)
,(NULL,NULL,'P007',NULL,'2015-02-12',1004863,NULL)
) t (sKodeMutasiP,OldPosition,NewPosition,ApprovedBy,ApprovedDate,Nip,KodePenilaian)
)
select top(1) NewPosition, ApprovedDate
from (
select NewPosition,ApprovedDate
, grp = row_number() over(order by ApprovedDate desc) - row_number() over(partition by NewPosition order by ApprovedDate desc)
from HistoryPosition
where nip = 1004863
) t
where grp = 0
order by ApprovedDate;
EDIT2
Use this snippet in OUTER APPLY instead of LEFT JOIN as it depends on other table data:
...
outer apply(
select top(1) NewPosition, ApprovedDate
from (
select NewPosition,ApprovedDate
, grp = row_number() over(order by ApprovedDate desc) - row_number() over(partition by NewPosition order by ApprovedDate desc)
from HistoryPosition hp
where hp.nip = a.nip -- other table
) t
where grp = 0
order by ApprovedDate
) npa
...
If your question is, how can I combine two result sets so that they appear in a single row, the following select can be used:
-- first select
select 1 one, 2 two, 3 three, 0 joinCondition
-- second select
select 'a' a, 'b' b, 'c' c, 0 joinCondition
-- combined
select one, two, three, a, b, c
from (select 1 one, 2 two, 3 three, 0 joinCondition) first
inner join (select 'a' a, 'b' b, 'c' c, 0 joinCondition) second
on first.joinCondition = second.joinCondition
The idea is, we add a dummy column to both selects with equal value so that it can be used to join them
I need to find out how to generate an alphanumeric string that follows the format like in the answer for this question which I'm currently using, except it has to be in the following format:
Vowel + consonant + vowel + consonant + 4-digit number
For example ABAB1111 or IJUZ9236.
Thanks for any suggestion.
You can follow this steps:
Generate a vowels(A,E...) table , consonants (B,C..) table and numbers (1,2,..) table .
Then use this query:
SELECT (SELECT TOP 1 * FROM vowels ORDER BY newid()) +
(SELECT TOP 1 * FROM consonants ORDER BY newid()) +
(SELECT TOP 1 * FROM vowels ORDER BY newid()) +
(SELECT TOP 1 * FROM consonants ORDER BY newid()) +
(SELECT TOP 1 * FROM numbers ORDER BY newid()) +
(SELECT TOP 1 * FROM numbers ORDER BY newid()) +
(SELECT TOP 1 * FROM numbers ORDER BY newid()) +
(SELECT TOP 1 * FROM numbers ORDER BY newid())
I assume you want a random string. Something like this should work:
with v as (
select 'A' as c union all select 'E' union all . . .
),
c as (
select 'B' as c union all select 'C' union all . . .
),
d as (
select '0' as c union all select '1' union all . . .
)
select ((select top 1 c from v order by newid()) +
(select top 1 c from c order by newid()) +
(select top 1 c from v order by newid()) +
(select top 1 c from c order by newid()) +
(select top 1 c from d order by newid()) +
(select top 1 c from d order by newid()) +
(select top 1 c from d order by newid()) +
(select top 1 c from d order by newid())
);
Using temp tables as example data i'd do it like this;
CREATE TABLE #Vowels (Vowel varchar(1))
INSERT INTO #Vowels VALUES ('A'),('E'),('I'),('O'),('U')
CREATE TABLE #Consonants (Consonant varchar(1))
INSERT INTO #Consonants VALUES ('B'),('C'),('D'),('F'),('G'),('H'),('J'),('K'),('L'),('M'),('N'),('P'),('Q'),('R'),('S'),('T'),('V'),('W'),('X'),('Y'),('Z')
CREATE TABLE #Numbers (Numbers varchar(1))
INSERT INTO #Numbers VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)
SELECT
v1.Vowel + c1.Consonant + v2.Vowel + c2.Consonant + n1.Numbers + n2.Numbers + n3.Numbers + n4.Numbers AS Result
FROM (SELECT TOP 1 Vowel FROM #Vowels ORDER BY NEWID()) v1
CROSS JOIN (SELECT TOP 1 Consonant FROM #Consonants ORDER BY NEWID()) c1
CROSS JOIN (SELECT TOP 1 Vowel FROM #Vowels ORDER BY NEWID()) v2
CROSS JOIN (SELECT TOP 1 Consonant FROM #Consonants ORDER BY NEWID()) c2
CROSS JOIN (SELECT TOP 1 Numbers FROM #Numbers ORDER BY NEWID()) n1
CROSS JOIN (SELECT TOP 1 Numbers FROM #Numbers ORDER BY NEWID()) n2
CROSS JOIN (SELECT TOP 1 Numbers FROM #Numbers ORDER BY NEWID()) n3
CROSS JOIN (SELECT TOP 1 Numbers FROM #Numbers ORDER BY NEWID()) n4
DROP TABLE #Consonants
DROP TABLE #Numbers
DROP TABLE #Vowels
The result comes out like this but with different values each time you run it.
Result
AQOF7641
If you are running this a number of times, it would make sense to make proper tables containing your vowels, consonants and number. It would reduce the (admittedly small) cost of this query.
This should do the trick:
WITH letters as
(
SELECT 'bcdfghjklmnpqrstvwxyz' c, 'aeiou' v
)
,CTE as
(
SELECT
SUBSTRING(v, CAST(rand()*5 as int)+1, 1)+
SUBSTRING(c, CAST(rand()*21 as int)+1, 1)+
SUBSTRING(v, CAST(rand()*5 as int)+1, 1)+
SUBSTRING(c, CAST(rand()*21 as int)+1, 1)+
right(10000+ CAST(rand()*10000 as int),4) x
FROM letters
)
SELECT x
FROM CTE
DECLARE #AlphaString VARCHAR(200) = NULL;
WITH
CTE_Digits AS (
SELECT TOP 255
ROW_NUMBER() OVER (ORDER BY a.object_id) AS RowNum
FROM
sys.all_columns a
CROSS JOIN
sys.all_columns b),
CTE_Types AS (
SELECT
CHAR(RowNum) AS Digit,
CASE
WHEN RowNum < 58 THEN 'D'
WHEN CHAR(RowNum) IN ('A','E','I','O','U') THEN 'V'
ELSE 'C'
END AS CharType
FROM
CTE_Digits
WHERE
RowNum BETWEEN 48 AND 57
OR RowNum BETWEEN 65 AND 90),
CTE_List AS (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY CharType ORDER BY NEWID()) AS NewRow
FROM
CTE_Types),
CTE_Ordered AS (
SELECT
*,
CASE CharType
WHEN 'V' THEN 2
WHEN 'C' THEN 3
WHEN 'D' THEN 7
END * NewRow AS DigitOrder
FROM
CTE_List
WHERE
(NewRow < 5
AND CharType = 'D')
OR NewRow < 3)
SELECT #AlphaString =
(SELECT
CAST(Digit AS VARCHAR(MAX))
FROM
CTE_Ordered
ORDER BY
DigitOrder
FOR XML PATH(''));
SELECT #AlphaString;
create table #middle
(
A INT,
B INT,
C INT
)
INSERT INTO #middle (A,B,C) VALUES (7,6,2),(1,0,8),(9,12,16),(7, 16, 2),(1,12,8), (9,12,16),(9,12,16),(7, 16, 2),(1,12,8), (9,12,16)
;WITH MIDS
AS (SELECT *,
Row_number()
OVER (
ORDER BY a, b, c DESC )AS rn
FROM #middle)
SELECT *
FROM MIDS
WHERE rn <= (SELECT CASE ( Count(*)%2 )
WHEN 0 THEN ( Count(*) / 2 ) + 1
ELSE ( Count(*) / 2 )
END
FROM MIDS) except (SELECT *
FROM MIDS
WHERE rn < (SELECT ( Count(*) / 2 )
FROM MIDS))
The query i have tried works >4 records but not for '3'.Now my question is how should i modify my query so that for 3 records i should get the 2nd record which is the middle most record among them,try to insert only 3 records from above records and help. Thanks in advance.
You can use OFFSET and FETCH
select *
from #middle
order by a, b, c desc
offset (select count(*) / 2 - (case when count(*) % 2 = 0 then 1 else 0 end) from #middle) rows
fetch next (select 2 - (count(*) % 2) from #middle) rows only
There are many ways to get the median in SQL. Here is a simple way:
select h.*
from (select h.*, row_number() over (order by a, b, c desc) as seqnum,
count(*) over () as cnt
from #highest h
) h
where 2 * rn in (cnt, cnt - 1, cnt + 1);
For an even number of records, you will get two rows. You need to decide what you actually want in this case.
How about this:
**EDITED
;WITH MIDS
AS (SELECT *,
Row_number()
OVER (
ORDER BY a, b, c DESC )AS rn
FROM #middle),
Cnt
AS
(SELECT COUNT(*) c, COUNT(*)%2 as rem, COUNT(*)/2 as mid FROM Mids)
SELECT *
FROM MIDS
CROSS APPLY cnt
where (rn >= cnt.mid and rn <= cnt.mid + 1 AND cnt.rem = 0) OR
(cnt.rem <> 0 AND rn = cnt.mid+1)
I have this query and I want to get "page" variable which is created:
SELECT *, (rowNum / 5) + 1 as page
FROM (
SELECT *, Row_Number() OVER (ORDER BY items.id_item ASC) as rowNum
FROM items INNER JOIN utilizadores ON items.autor = utilizadores.id_user
) x
WHERE (rowNum / 1000) + 1 = 1
How can I get it in the query to make a procedure to search.
CREATE PROCEDURE get_items_by_page
#page int
AS
SELECT *, (rowNum / 5) + 1 as page
FROM (
SELECT *, Row_Number() OVER (ORDER BY items.id_item ASC) as rowNum
FROM items INNER JOIN utilizadores ON items.autor = utilizadores.id_user
) x
WHERE (rowNum / 1000) + 1 = 1 //the required condition to query is in bottom
GO
and page = #page;
CREATE PROCEDURE get_items_by_page
#page int
AS
SELECT x.*, (rowNum / 5) + 1 as page
FROM (
SELECT *, Row_Number() OVER (ORDER BY items.id_item ASC) as rowNum
FROM items INNER JOIN utilizadores ON items.autor = utilizadores.id_user
) x
WHERE (rowNum / 5) + 1 = #page
GO
I ve got the following query which is throwing the following error
Unkown Column 'RowNum'
WITH Employees AS
(
SELECT
(keyTblSp.RANK * 3) AS [Rank],
sp.*,
addr.Street,
addr.PostOfficeBox,
addr.StreetNumber
FROM Employee sp
INNER JOIN
FREETEXTTABLE(Employee, *, 'something', 1000) AS keyTblSp
ON sp.EmployeeId = keyTblSp.[KEY]
LEFT OUTER JOIN [Address] addr ON addr.EmployeeId = sp.EmployeeId
UNION ALL
SELECT
(keyTblAddr.RANK * 2) AS [Rank],
sp.*,
addr.Street,
addr.PostOfficeBox,
addr.StreetNumber
FROM Employee sp
LEFT OUTER JOIN [Address] addr ON addr.EmployeeId = sp.EmployeeId
INNER JOIN
FREETEXTTABLE([Address], *, 'something', 1000) AS keyTblAddr
ON addr.AddressId = keyTblAddr.[KEY]
)
SELECT ROW_NUMBER() OVER (ORDER BY [Rank] DESC) AS RowNum, *
FROM Employees
WHERE RowNum BETWEEN (1 - 1) * 10 + 1 AND 1 * 10
ORDER BY Rank DESC
This is because aliases are not recognized in WHERE clauses. Instead, use the full query like this:
WHERE ROW_NUMBER() OVER (ORDER BY [Rank] DESC) BETWEEN (1 - 1) * 10 + 1 AND 1 * 10
Try wrpping up your query to get the name usable in the where clause
SELECT
*
FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY [Rank] DESC) AS RowNum
, *
FROM
Employees) AS Results
WHERE
RowNum BETWEEN (1 - 1) * 10 + 1 AND 1 * 10
ORDER BY
Rank
Your WHERE clause cannot refer to a window or aggregate function like ROW_NUMBER(). If you want to filter on the result of ROW_NUMBER(), you need to do so in the HAVING clause:
...
SELECT ROW_NUMBER() OVER (ORDER BY [Rank] DESC) AS RowNum, *
FROM Employees
HAVING RowNum BETWEEN (1 - 1) * 10 + 1 AND 1 * 10
ORDER BY Rank DESC
How about:
select top 10 *
from Employees
order by Rank Desc
Alternatively, does it work without the where rownum clause. (why is your between so tricky?).