Sql Server Alias name in Row_Number function - sql

select tmp.id, tmp.portfolio,
ROW_NUMBER() OVER(order by tmp.id DESC) AS RowNum
from
(select r.portfolio, r.id
from research r
where r.created_by = 'Adam Cohen'
) as tmp
WHERE RowNum BETWEEN 5 AND 10;
I am not able refer the RowNum in the where condition, as it shows that Invalid column name 'RowNum'. Kindly help me to use the right syntax to get the result.
Edit - Changed Requirement
SELECT * FROM
(
select id, portfolio,
CASE WHEN l.posted_on IS NULL
THEN CONVERT(VARCHAR(40),l.created_on,120)
ELSE CONVERT(VARCHAR(40),l.posted_on,120)
END AS sort_by,
ROW_NUMBER() OVER(order by sort_by DESC) AS RowNum
from research
where created_by = 'Adam Cohen'
) x
WHERE x.RowNum BETWEEN 5 AND 10
I tried to include the Row_Number function like above but I got the sort_by as invalid column.

You'll need to wrap your projection in a derived table, although you can drop the inner tmp table:
SELECT * FROM
(
select id, portfolio,
ROW_NUMBER() OVER(order by id DESC) AS RowNum
from
research
where created_by = 'Adam Cohen'
) x
WHERE x.RowNum BETWEEN 5 AND 10
Edit
Note that if you don't actually need the pseudo row number in the final select, that since Sql 2012, in your 'page of data' scenario, that you will be able to use OFFSET FETCH apply the without the need for ROW_NUMBER() or derived tables at all:
select id, portfolio
from research
where created_by = 'Adam Cohen'
order by id desc
offset 5 rows fetch next 6 rows only;
Edit #2, Re new requirements
CASE WHEN l.posted_on IS NULL
THEN CONVERT(VARCHAR(40),l.created_on,120)
ELSE CONVERT(VARCHAR(40),l.posted_on,120)
END AS sort_by
Can be more concisely expressed as
CONVERT(VARCHAR(40), COALESCE(posted_on, created_on)) AS AS sort_by
However, if you still need original row number, you also use this projection in the ORDER BY of the windowing function (OVER), in order to DRY this up you will need the nested derived table. You can still use the SQL 2012 OFFSET / FETCH NEXT to paginate, however:
SELECT *,
ROW_NUMBER() OVER(order by sort_by DESC) AS RowNum
FROM
(
SELECT id, portfolio, CONVERT(VARCHAR(40), COALESCE(posted_on, created_on)) AS sort_by
from research
where created_by = 'Adam Cohen'
) y
ORDER BY id DESC
OFFSET 5 ROWS FETCH NEXT 6 ROWS ONLY;

You need to nest the ROW_NUMBER in the Derived Table:
select tmp.id, tmp.portfolio, tmp.RowNum
from
(select r.portfolio, r.id,
ROW_NUMBER() OVER(order by r.id DESC) AS RowNum
from research r
where r.created_by = 'Adam Cohen'
) as tmp
WHERE RowNum BETWEEN 5 AND 10;

Related

Return second from the last oracle sql

SELECT * FROM
(
SELECT DISTINCT(TRUNC(receipt_dstamp))
FROM inventory
WHERE substr(location_id,1,3) = 'GI-'
ORDER BY 1 ASC
)
WHERE ROWNUM <= 5
Output:
Hi all, i've got this subeqery and in this case my oldest date is in row 1, i want to retrive only second from the last(from the top in this case) which is gonna be 01-SEP-21.
I was trying to play with ROWNUM and OVER but without any results, im getting blank output.
Thank you.
Full query:
SELECT TRUNC(receipt_dstamp) as old_putaway_date, COUNT(tag_id) as tag_old_putaway
FROM inventory
WHERE substr(location_id,1,3) = 'GI-'
AND TRUNC(receipt_dstamp) IN (
SELECT * FROM
(
SELECT DISTINCT(TRUNC(receipt_dstamp))
FROM inventory
WHERE substr(location_id,1,3) = 'GI-'
ORDER BY 1 ASC
)
WHERE ROWNUM = 1
)
GROUP BY TRUNC(receipt_dstamp);
You should be able to simplify the entire query to:
SELECT old_putaway_date,
COUNT(tag_id) as tag_old_putaway
FROM (
SELECT TRUNC(receipt_dstamp) as old_putaway_date,
tag_id,
DENSE_RANK() OVER (ORDER BY TRUNC(receipt_dstamp)) AS rnk
FROM inventory
WHERE substr(location_id,1,3) = 'GI-'
)
WHERE rnk = 3
GROUP BY
old_putaway_date;
You can use dense_rank() :
SELECT * FROM (
SELECT L.*,DENSE_RANK()
OVER (PARTITION BY L.TAG_OLD_PUTAWAY ORDER BY L.OLD_PUTAWAY_DATE DESC) RNK
FROM
(
SELECT TRUNC(receipt_dstamp) as old_putaway_date, COUNT(tag_id) as tag_old_putaway
FROM inventory
WHERE substr(location_id,1,3) = 'GI-'
AND TRUNC(receipt_dstamp) IN (
SELECT * FROM
(
SELECT DISTINCT(TRUNC(receipt_dstamp))
FROM inventory
WHERE substr(location_id,1,3) = 'GI-'
ORDER BY 1 ASC
)
WHERE ROWNUM = 1
)
GROUP BY TRUNC(receipt_dstamp)
) L
) WHERE RNK = 2
You are using an old Oracle syntax that is not standard compliant in the regard that it relies on a subquery result order. (Sub)query results are unordered data sets by definition, but Oracle lets this pass in order to make their ROWNUM work with it.
Oracle now supports the standard SQL FETCH clause, which you should use instead.
SELECT DISTINCT TRUNC(receipt_dstamp) AS receipt_date
FROM inventory
WHERE SUBSTR(location_id, 1, 3) = 'GI-'
ORDER BY receipt_date
OFFSET 2 ROWS
FETCH NEXT 1 ROW ONLY;
https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html#GUID-CFA006CA-6FF1-4972-821E-6996142A51C6

Select every second record then determine earliest date

I have table that looks like the following
I have to select every second record per PatientID that would give the following result (my last query returns this result)
I then have to select the record with the oldest date which would be the following (this is the end result I want)
What I have done so far: I have a CTE that gets all the data I need
WITH cte
AS
(
SELECT visit.PatientTreatmentVisitID, mat.PatientMatchID,pat.PatientID,visit.RegimenDate AS VisitDate,
ROW_NUMBER() OVER(PARTITION BY mat.PatientMatchID, pat.PatientID ORDER BY visit.VisitDate ASC) AS RowNumber
FROM tblPatient pat INNER JOIN tblPatientMatch mat ON mat.PatientID = pat.PatientID
LEFT JOIN tblPatientTreatmentVisit visit ON visit.PatientID = pat.PatientID
)
I then write a query against the CTE but so far I can only return the second row for each patientID
SELECT *
FROM
(
SELECT PatientTreatmentVisitID,PatientMatchID,PatientID, VisitDate, RowNumber FROM cte
) as X
WHERE RowNumber = 2
How do I return the record with the oldest date only? Is there perhaps a MIN() function that I could be including somewhere?
If I follow you correctly, you can just order your existing resultset and retain the top row only.
In standard SQL, you would write this using a FETCH clause:
SELECT *
FROM (
SELECT
visit.PatientTreatmentVisitID,
mat.PatientMatchID,
pat.PatientID,
visit.RegimenDate AS VisitDate,
ROW_NUMBER() OVER(PARTITION BY mat.PatientMatchID, pat.PatientID ORDER BY visit.VisitDate ASC) AS rn
FROM tblPatient pat
INNER JOIN tblPatientMatch mat ON mat.PatientID = pat.PatientID
LEFT JOIN tblPatientTreatmentVisit visit ON visit.PatientID = pat.PatientID
) t
WHERE rn = 2
ORDER BY VisitDate
OFFSET 0 ROWS FETCH FIRST 1 ROW ONLY
This syntax is supported in Postgres, Oracle, SQL Server (and possibly other databases).
If you need to get oldest date from all selected dates (every second row for each patient ID) then you can try window function Min:
SELECT * FROM
(
SELECT *, MIN(VisitDate) OVER (Order By VisitDate) MinDate
FROM
(
SELECT PatientTreatmentVisitID,PatientMatchID,PatientID, VisitDate,
RowNumber FROM cte
) as X
WHERE RowNumber = 2
) Y
WHERE VisitDate=MinDate
Or you can use SELECT TOP statement. The SELECT TOP clause allows you to limit the number of rows returned in a query result set:
SELECT TOP 1 PatientTreatmentVisitID,PatientMatchID,PatientID, VisitDate FROM
(
SELECT *
FROM
(
SELECT PatientTreatmentVisitID,PatientMatchID,PatientID, VisitDate,
RowNumber FROM cte
) as X
WHERE RowNumber = 2
) Y
ORDER BY VisitDate
For simplicity add order desc on date column and use TOP to get the first row only
SELECT TOP 1 *
FROM
(
SELECT PatientTreatmentVisitID,PatientMatchID,PatientID, VisitDate, RowNumber FROM cte
) as X
WHERE RowNumber = 2
order by VisitDate desc

oracle sql wih rownum <=

why below query is not giving results if I remove the < sign from query.Because even without < it must match with results?
Query used to get second max id value:
select min(id)
from(
select distinct id
from student
order by id desc
)
where rownum <=2
student id
1
2
3
4
Rownum has a special meaning in Oracle. It is increased with every row, but the optimizer knows that is increasing continuously and all consecutive rows must met the rownum condition. So if you specify rownum = 2 it will never occur since the first row is already rejected.
You can see this very nice if you do an explain plan on your query. It will show something like:
Plan for rownum <=:
COUNT STOPKEY
Plan for rownum =:
FILTER
A ROWNUM value is not assigned permanently to a row (this is a common misconception). A row in a table does not have a number; you cannot ask for row 2 or 3 from a table
click Here for more Info.
This is from the link provided:
Also confusing to many people is when a ROWNUM value is actually assigned. A ROWNUM value is assigned to a row after it passes the predicate phase of the query but before the query does any sorting or aggregation. Also, a ROWNUM value is incremented only after it is assigned, which is why the following query will never return a row:
select *
from t
where ROWNUM > 1;
Because ROWNUM > 1 is not true for the first row, ROWNUM does not advance to 2. Hence, no ROWNUM value ever gets to be greater than 1. Consider a query with this structure:
select ..., ROWNUM
from t
where <where clause>
group by <columns>
having <having clause>
order by <columns>;
I think this is the query you are looking for:
select id
from (select distinct id
from student
order by id desc
) t
where rownum <= 2;
Oracle processes the rownum before the order by, so you need a subquery to get the first two rows. The min() was forcing an aggregation that returned only one result, but before the rownum was applied.
If you actually want only the second value, you need an additional layer of subqueries:
select min(id)
from (select id
from (select distinct id
from student
order by id desc
) t
where rownum <= 2
) t;
However, I would do:
select id
from (select id, dense_rank() over (order by id) as seqnum
from student
) t
where seqnum = 2;
Order asc instead of desc
select id from student where rownum <=2 order by id asc;
Why not just use
select id
from ( select distinct id
, row_number() over (order by id desc) x
from student
)
where x = 2
Or even really bad. Getting the count and index :)
select id
from ( select id
, row_number() over (order by id desc) idx
, sum(1) over (order by null) cnt
from student
group
by id
)
where idx = cnt - 1 -- get the pre-last
Or
where idx = cnt - 2 -- get the 2nd-last
Or
where idx = 3 -- get the 3rd
Try this
SELECT *
FROM (
SELECT id, row_number() over (order by id asc) row_num
FROM student
) AS T
WHERE row_num = 2 -- or 3 ... n
ROW_NUMBER

PostgreSQL - Assigning window function to alias

I'm trying to set ROW_NUMBER()... as an alias so I can reference it in the OFFSET. e.g. OFFSET some_alias - 1. I need to get a single row including the ROW_NUMBER() from a larger query. Here's my working code (gets correct ROW_NUMBER(), but isn't offset by the right amount):
WITH FirstQuery AS (
SELECT "RepInitials", COUNT("OrderStatus"), ROW_NUMBER()OVER(ORDER BY COUNT("OrderStatus") DESC)
FROM "tblBulkSalesQuery"
WHERE "OrderStatus" = 'CMC'
GROUP BY "RepInitials"
)
SELECT "RepInitials", COUNT("OrderStatus"), ROW_NUMBER()OVER(ORDER BY COUNT("OrderStatus") DESC)
FROM "tblBulkSalesQuery"
WHERE "OrderStatus" = 'CMC'
GROUP BY "RepInitials"
LIMIT 1
OFFSET 1;
select *
from (
SELECT "RepInitials",
COUNT("OrderStatus") as order_status_count,
ROW_NUMBER() OVER (ORDER BY COUNT("OrderStatus") DESC) as rn
FROM "tblBulkSalesQuery"
WHERE "OrderStatus" = 'CMC'
GROUP BY "RepInitials"
) as t
where rn = 1
Edit:
The t is an alias for the nested select ("derived table"). PostgreSQL requires each derived table to get it's own "name" and that can only be done by assigning a alias.
It's pretty much the same as:
with t as (
... here goes the real select ...
)
select *
from t
where rn = 1;

Select Nth Row From A Table In Oracle

How can I select the Nth row from a table in Oracle?
I tried
SELECT PRICE FROM AAA_PRICING WHERE ROWNUM = 2
but that didn't work. Please help!
Based on the classic answer:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:127412348064
select *
from ( select a.*, rownum rnum
from ( YOUR_QUERY_GOES_HERE -- including the order by ) a
where rownum <= N_ROWS )
where rnum >= N_ROWS
/
Will not works with '=' (will works <2 or >2, but not equal)
so you can
SELECT Price from (SELECT PRICE, ROWNUM AS RN FROM AAA_PRICING) WHERE RN = 2
To address the reason for this:
The RowNum is a pseudo-column supplied by Oracle. It is generated while the SELECT-clause is being processed. Since the WHERE-clause is handled before the SELECT-clause, the RowNum does not have a proper value yet.
One can argue whether or not it makes sense to have Oracle throw an exception in situation, but because RowNum still is a pseudo-column it's still valid to have it there.
Note: Don't confuse this with RowId, which is an entire different story!
IMPORTANT EDIT:
Note that what I wrote about RowNum is only true for =, >, >=, IN () and maybe others. If you check for, e.g. RowNum < 10, you only get nine records!? I don't know why that is the case!
Select * From
(
Select Row_Number() OVER (Order by empno) rno, e.*
From scott.emp e
)
Where rno in (1, 3, 11)
SELECT PRICE
FROM (
SELECT PRICE,
ROWNUM rnum
FROM AAA_PRICING
ORDER BY PRICE ASC
)
WHERE rnum = 2
If you are on Oracle 12 or above, You can use the result offset and fetch clauses:
SELECT PRICE FROM AAA_PRICING
offset 1 rows fetch next 1 rows only
SELECT * FROM
(SELECT PRICE, ROWNUM AS RN FROM AAA_PRICING )
WHERE RN = 2;
select * from (Select Price, rownum as rn from(Select * from AAA_PRICING a order by a.Price))
where rn=2;
It will give you 2nd lowest price from the Price column. If you want simply 2nd row remove Order By condition.
ROWNUM is a pseudo column which generates unique pseudo values (equals to the number of records present in the SELECT statement o/p) during the execution of SELECT clause. When this pseudo column is specified with the WHERE clause it's value becomes 1 by default. So it behaves according to the comparison operator specified with it.
SELECT * FROM (
SELECT ROWNUM RN, E.*
FROM Emp E
)
WHERE RN = 10;
select *
From (select PRICE, DENSE_RANK() over(ORDER BY PRICE desc) as RNO
From AAA_PRICING
) t where RNO=2;
select a.*, rownum rnum
from ( select * from xyz_menu order by priority desc) a
where rownum < 5 ;
select * from xyz_menu order by priority desc
creating virtual table and also defining row number in virtual table
note: for oracle
Problem solved!
To select 2nd row in Oracle..
select SEN_NO,ITEM_NO from (select * from master_machine where
sen_no ='BGCWKKL23' and rownum <=2 order by
rownum desc,timestamp asc) where rownum <=1
Thank You!