Let say I have this below data in my table for instance:
If I use group by clause based on wonum, then we will see only 2 records from wonum,
if we group by WONUM, STATUS even then changedate will not display and we will not get our required output.
Therefore, we need to group them and then count rows in each group , and based on the count we can apply any condition.
let's do it using ROW_NUMBER() function:
ROW_NUMBER()OVER ( [partition_clause optional] order_by_clause)
let's write our query:
SELECT *from(SELECT wonum, STATUS, changedate, row_number()over (PARTITION BY wonum ORDER BY changedate) AS rankFROM WOstatus wWHERE W.WONUM IN ('42451047', '37778572')--GROUP BY wonum, status,changedate) countWHERE rank <=2
Explanation:
we added a function (run_number() over) and make a partition/group by wonum ) give it a name as rank.
2. make this query as a child of another FROM clause ,
3. and in WHERE clause we put our condition to display only selected records because now we have a new column as rank.
The same thing can be in Excel:
No comments:
Post a Comment