on 2022 Jan 12 10:50 AM
Is it possible to generate rowid over partition in a dataset?
In the example below, I need to see a counter within each department, in other words I need another column in which I can see Mary is 1st in accounting and John is 2nd in accounting, then the counter starts from 1 for the next depart ....
create or replace table mytest(depart varchar(10), employee varchar(10), salary double);
insert into mytest values
('accounting', 'John', 2800),
('accounting', 'Mary', 2450),
('technical', 'Sarah', 3100),
('technical', 'Wolfgang', 3300),
('admin', 'George', 4200)
select depart, employee, salary, sum(salary) over (partition by depart) from mytest order by depart, salary
row_number() is your friend:
select depart, row_number() over (partition by depart order by salary) as emp_no_per_depart, employee, salary, sum(salary) over (partition by depart) as depart_salary_sum from mytest order by depart, salary;
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Thanks for the reply, it works exactly as I want.
One more question, I see that the order by salary is mandatory in the first over partition, does it but really matter? I mean can I write it also so?
select depart,
row_number() over (partition by depart order by depart) as
emp_no_per_depart,
employee, salary,
sum(salary) over (partition by depart) as depart_salary_sum
from mytest
order by depart, salary;
Well, the ORDER BY within the window definition specifies how the rows are numbered within each partition. Using the same expression for PARTITION BY and ORDER BY is certainly legal – but would mean you do not really specify an order, and the query engine is free to number the rows within each partition randomly. That's similar to omitting the final ORDER BY.
Here's a sample with your OVER clause but a different final ORDER BY including the row number, and in my tests, now "John" is accidentally numbered 1 within the accounting department.
select depart, row_number() over (partition by depart order by depart) as emp_no_per_depart, employee, salary, sum(salary) over (partition by depart) as depart_salary_sum from mytest order by depart, emp_no_per_depart;
I can't tell whether that "vague order" is sufficient for you.
User | Count |
---|---|
67 | |
8 | |
8 | |
6 | |
6 | |
6 | |
6 | |
6 | |
5 | |
5 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.