Performing Top-n Analysis (but per group)
The Oracle University Guide SQL Volume 2 says:
To perform Top-n Analysis the general syntax is
SELECT [column_list], ROWNUM
FROM (SELECT [column_list]
FROM table
ORDER BY Top-N_column)
WHERE ROWNUM <= N;
for example
To display the top three earner names and salaries
from the EMPLOYEES table.
SELECT ROWNUM as RANK, last_name, salary
FROM (SELECT last_name,salary FROM employees
ORDER BY salary DESC)
WHERE ROWNUM <= 3;
or to display the four most senior employees in the company.
SELECT ROWNUM as SENIOR,E.last_name, E.hire_date
FROM (SELECT last_name,hire_date FROM employees
ORDER BY hire_date)E
WHERE rownum <= 4;
but what about if I have groups? for example if I want to display the 3 top earners per department?
In my case now
I want to fetch the top 4 items per category, with the biggest quantity (posothta)
SELECT ROWNUM as RANK,
H.KATHG_EIDOYS,
H.KATHG_EIDOYS_DESCR,
H.EIDOS,
H.EIDOS_DESCR,
H.CODE_SUP_BASIKOS_NAME,
H.RAFI_CODE,
H.LINES,
H.POSOTHTA
from (
SELECT B.KATHG_EIDOYS,
D.DESCRIPTION KATHG_EIDOYS_DESCR,
B.CODE EIDOS,
B.DESCRIPTION EIDOS_DESCR,
S.NAME CODE_SUP_BASIKOS_NAME,
C.RAFI_CODE,
COUNT(A.FLD_SEQ_NUM) LINES,
nvl(SUM(decode(k.INV_APOGRAFH_FLAG,'0', decode(k.INV_EXAGOGH_POSOTHTA,1, a.POSOTHTA_TIMOLOGHSHS,2,-a.POSOTHTA_TIMOLOGHSHS))),0) POSOTHTA
FROM ERP_EIDOI_ANA_RAFI C,
ERP_KODIKOI_KINHSHS K,
ERP_POLHSEIS_DETAILS A,
ERP_SUP_CUST S,
ERP_KATHG_EIDON D,
ERP_EIDH b
WHERE B.COMPANY = DECODE(1,1,'9',B.COMPANY)
AND a.COMPANY_KK=K.COMPANY
AND a.KK_CODE=K.CODE
and A.company_WAREHOUSE = c.COMPANY_WARE(+)
and A.MASTER_WAREHOUSE = c.MASTER_WARE_CODE(+)
and A.CODE_WAREHOUSE = c.DETAIL_WARE_CODE(+)
and A.COMPANY_EIDOS = c.COMPANY_EIDOS(+)
and A.EIDOS = c.CODE_EIDOS (+)
AND C.DEFAULT_FLAG (+)= 1
AND b.code = a.EIDOS
and b.company = a.COMPANY_EIDOS
AND D.CODE= B.KATHG_EIDOYS
AND D.COMPANY= B.COMPANY_KATHG_EIDOYS
AND B.COMPANY_SUP_BASIKOS = S.COMPANY
AND B.CODE_SUP_BASIKOS = S.CODE
AND B.PROMHTHEYTHS_FLAG_BASIKOS = S.PELATHS_PROMHTHEYTHS_FLAG
AND /*&p_where*/
a.COMPANY='9' and (a.group_source) = '10' and (A.MASTER_WAREHOUSE) = '01' and (A.CODE_WAREHOUSE) = '0101' and (a.hmerom_parast) >= to_date('01/01/2006','dd/mm/rrrr') and (a.hmerom_parast) <= to_date('25/05/2006','dd/mm/rrrr')
GROUP BY B.KATHG_EIDOYS, D.DESCRIPTION, B.CODE, B.DESCRIPTION, S.NAME,C.RAFI_CODE
ORDER BY 8 DESC
) H
where 1=1 and ROWNUM <= 4
this select does not bring me the desired results, because if for example
category 01 has 10 items
and category 02 has 2 items,
this select will bring me only the first four rows
and not the items from the 02 category.
If you understand what is the case I will wait for your replies.
Thanks in advance
Hi,
Here is an example. It gives you customers ids with highest salary per department.
SELECT CUSTOMER_ID, SALARY, RANK, DEPARTMENT
FROM (SELECT CUSTOMER_ID, SALARY, DEPARTMENT,
RANK() OVER (PARTITION BY DEPARTMENT ORDER BY SALARY DESC) AS RANK
FROM TABLEA)
WHERE RANK < 2;
Peter D.
Similar Messages
-
An Oracle University Material in Sql Says
The high-level structure of a Top-N analysis query is:
SELECT [column_list], ROWNUM
FROM (SELECT [column_list]
FROM table
ORDER BY Top-N_column)
WHERE ROWNUM <= N;
For example to display the top three earner names and salaries from the EMPLOYEES table:
SELECT ROWNUM as RANK, last_name, salary
FROM (SELECT last_name,salary FROM employees
ORDER BY salary DESC)
WHERE ROWNUM <= 3;
My question is
If, instead of this query, I write
1)
SELECT ROWNUM as RANK, last_name, salary
FROM employees
WHERE ROWNUM <= 3
ORDER BY salary DESC
or
2)
SELECT ROWNUM as RANK, last_name, salary
FROM ( SELECT last_name,salary
FROM employees
WHERE ROWNUM <= 3
ORDER BY salary DESC
is any difference?
The results in schema hr are the same.............
Thank youis any difference? yes, there is!
SQL> with t as (select 1 num from dual union all
2 select 4 from dual union all
3 select 3 from dual union all
4 select 2 from dual)
5 --
6 SELECT ROWNUM as RANK, num
7 FROM (SELECT num FROM t ORDER BY num desc)
8 WHERE ROWNUM <= 3;
RANK NUM
1 4
2 3
3 2
SQL>
SQL> with t as (select 1 num from dual union all
2 select 4 from dual union all
3 select 3 from dual union all
4 select 2 from dual)
5 --
6 SELECT ROWNUM as RANK, num
7 FROM t
8 WHERE ROWNUM <= 3
9 ORDER BY num DESC
10 /
RANK NUM
2 4
3 3
1 1
SQL>
SQL> with t as (select 1 num from dual union all
2 select 4 from dual union all
3 select 3 from dual union all
4 select 2 from dual)
5 --
6 SELECT ROWNUM as RANK, num
7 FROM (SELECT num FROM t
8 WHERE ROWNUM <= 3
9 ORDER BY num DESC)
10 /
RANK NUM
1 4
2 3
3 1
SQL> rownum is confered before ordering is made.
Thats why you should place the subquery with ordering in the inline view. -
What is Top-N analysis.?? can some one explain. I encountered this while going thru
the Sql book
The ORDER BY clause in the subquery is not
needed unless you are performing Top-N analysis.That means you are doing something like this in order to get top five paid people::
SELECT * FROM
( SELECT empno, ename, sal+nvl(comm,0) as remuneration
FROM emp
ORDER BY remuneration DESC )
WHERE rownum <= 5
/We have to do the ORDER BY in a sub-query because rownum gets applied before the rows are sorted.
Cheers, APC -
I have a project that is approximately 1 hour in length. This is the first project I am attempting to burn. I assigned a theme to the project and then proceeded to burn a DVD. Before the burn could actually start, PE crashed with a "blue screen" dump. I rebooted in Windows safe mode, then rebooted back into normal Windows mode. When I started PE and opened the project, nearly all of the themes were missing! It appears that only one theme per group remained.
What would have removed or hid the themes? I would have also expected all or none of the themes, rather than leaving just one per group. I was using a template in the "General" group, but the one that remained after the crash is not the one I had assigned to my project.
Does a reinstall restore the templates? If so, can I reinstall PE 4.0 from my CD without erasing, distroying, or losing the current projects I have created?
Thanks in advance for your comments!Hunt,
Before diving into the details of the items in the article, I did a few of the basic things:
stopped my anti-virus product (doh!)
stopped the temperature monitor software (doh!)
did a quick disk cleanup
turned off all trivial stuff in msconfig
I rebooted the system and started Premiere Elements. I had not attempted to reload the templates at that point, so I proceeded to "Burn to DVD". I selected the minimal quality and started the burn. That worked! Next I exited PE and restarted it and then was able to successfully "Burn to DVD" using the max setting for quality. As expected, it took a while to finish, but it also completed successfully! The resulting DVD looks and sounds great, so the rendering and burn phases seem to be working fine on my hardware.
I noticed on the CD that there is an option to load the themes, so I am going to try loading that today. I'll post more comments after I get the themes reloaded in case there are other steps involved in restoring those within the program. -
How to use top-n analysis in oracle 8i?
I mean,take a example.
I am maintaining a database of a 1000 employees.I want to display the names of the employees who are getting top 10 salaries(more further top 100 salaries) using a SQL query in oracle 8i only.Please answer my problem.Sorry, my suggestion will return 10 emp with highest salaries, not all employees with 10 highest salaries. To get all employees with 10 highest salaries in 8i:
SQL> SELECT ename,
2 sal
3 FROM emp
4 WHERE sal IN (
5 SELECT sal
6 FROM (
7 SELECT sal
8 FROM emp
9 GROUP BY sal
10 ORDER BY sal DESC
11 )
12 WHERE rownum <= 10
13 )
14 /
ENAME SAL
KING 5000
FORD 3000
SCOTT 3000
JONES 2975
BLAKE 2850
CLARK 2450
ALLEN 1600
TURNER 1500
MILLER 1300
MARTIN 1250
WARD 1250
ENAME SAL
ADAMS 1100
12 rows selected.
SQL> SY. -
Percentage based on Status using per group
Hi Gurus,
Can you help me with this? You have any approach of getting the percentage based on status using per group?
Currently I have this code below but it doesn’t have result but no error. I am trying to get the % In Complete.
<?xdofx:(sum(current-group()/NUMINCOMPLETE)/(sum(NUMSUBMITTED) + sum(NUMCOMPLETED) + sum(NUMINPROGRESS) + sum(NUMINCOMPLETE)))*100?>
Thanks Much,
JP
Edited by: BIPnewbie on Feb 6, 2012 3:05 AMUse this:
<?xdoxslt:div(sum(current-group()/NUMINCOMPLETE), ((sum(NUMSUBMITTED) + sum(NUMCOMPLETED) + sum(NUMINPROGRESS) + sum(NUMINCOMPLETE)))*100?>
Thanks,
Bipuser -
I have a scenario with the three nodes with server 2012 standard, each running an instance of SQL Server 2012 enterprise, participate in a
single Windows Server Failover Cluster (WSFC) that spans two data centers.
If the nodes in the primary data center are unavailable due to data center outage. Then how I can able to access node in the WSFC (Windows Server Failover Cluster) in the secondary disaster recovery data center automatically with some script.
I want to write script that can be able to check primary data center by pinging some IP after every 5 or 10 minutes.
If that IP is unable to respond then script can be able to Perform Forced Manual Failover of Availability Group (SQL Server) and WSFC (Windows Server Failover Cluster)
Can you please guide me for script writing for automatic failover in case of primary datacenter outage?You are trying to implement manually what should be happening automatically in the cluster. If the primary SQL Server becomes unavailable in the data center, it should fail over to the secondary SQL Server automatically. Is that not working?
You also might want to run this configuration by some SQL experts. I am not a SQL expert, but if you have both hosts in the data center in a cluster, there is no need for replication between those two nodes as they would be accessing
the database from some form of shared storage. Then it looks like you are trying to implement Always On to the DR site. I'm not sure you can mix both types of failover in a single configuration.
FYI, it would make more sense to establish a file share witness in your DR site instead of placing a third node in the data center for Node Majority quorum.
. : | : . : | : . tim -
How to perform power spectra analysis in DIAdem
Dear all:
I am a beginner in DIAdem but I have to complete my PhD thesis that is about the
analysis of rat EEG in DIAdem. I have acquired 10G data of rat EEG. I prefer the
power spectra method. Would someone please tell me:
1. How to perform power spectra analysis of multichannel EEG(8 channels) in
DIAdem? I hope the unit of the vertical axis is microV^2, but not dB ,nor
10*log10(microV^2/Hz).
2. How to calculate the absolute power and the relative power of EEG at a certain
frequency band in DIAdem? Is it possible to do it in DIAdem?
Thank you very much
Jing
[email protected]Hello,
It looks like you posted this question on a different thread. Please refer to this thread Duplicate Post for information about your question.
Regards,
Kevin L.
Applications Engineer
National Instruments -
TOP N analysis with same values
Dear Members,
Suppose we have the following data in the table Student.
Sname GPA
Jack 4.0
Smith 3.7
Rose 3.5
Rachel 3.5
Ram 2.8
I have seen many questions in this forum which gives good queries for TOP N analysis. But in my case those are not working.
There are total 5 students. I should write a query which should take an input and should give the students with top gpa as output in desc order.
Suppose if i give 4 as input i must get 4,3.7,3.5,3.5,2.8Gpa's since we have 2 gpa's which are same. Suppose i give 3 as the input i must get 4,3.7,3.5 and 3.5 GPA's.
The query must consider the GPA's which are same as one not different. How can we achive this. i.e the top three students (suppose input is 3) must be
Jack 4.0
Smith 3.7
Rose 3.5
Rachel 3.5
It must also include Rachel.
Any help is greatly appreciated.
Thanks
SandeepSQL> select * from test;
NAME GPA
Jack 4
Smith 3.7
Rose 3.5
Rachel 3.5
Ram 2.8
SQL> select name,gpa
2 from
3 (select name,gpa,dense_rank() over(order by gpa desc) rn
4 from test)
5 where rn <= 3
6 order by rn;
NAME GPA
Jack 4
Smith 3.7
Rose 3.5
Rachel 3.5 -
How to limit row number per group without change new page in crystal report
Hi All Expert,
Is there any way to limit row number per group without change new page in crystal report 2008. The reason i do that is due to customer using printer EPSON LQ 300 (dot matrix) always will print in landscape if detech my layout in landscape. Because they need the record always print in 1 page (Letter size) for 2 groups and each group must show 5 records. Example:
But, in CR2008, if you set the row per group from group section expert, definitely it will change to new page, but I do not want it change to new page. Any Idea?
In one page (Letter size):
Group Name: Customer-ABC
NO INVOICE AMOUNT
1) INV001 USD100
2) INV002 USD100
3) INV003 USD100
4) INV004 USD100
5) INV005 USD100
Group Name: Customer-ABC
NO INVOICE AMOUNT
6) INV006 USD100
7) INV007 USD100
8) INV008 USD100
9) INV009 USD100
10) INV010 USD100Hi Angie.....
I guess it is not possible.
Because if you have one common group for all the 10 records then in one page it will show 10 records under one group.
I mean i think it is not possible but m not completely sure......
Lets wait for expert advise....
Regards,
Rahul -
Performance Manager - Set Analysis
Hi
I am getting an error with BO Performance Manager - Set Analysis. I have created few sets (20) by logging in as a user. After that when i try to create new Sets - I am getting an error "0300-0101 Sets Cache Error : Maximum Number of Sets created for this User".
But when i login as a admin user/any other user I am able to create new Sets.
Please suggest.
Thanks
ArunaHi the soultion is simple log into Set Analyzer Architect go to Security then Profiles Select the User by Double Clicking the username Select the Limits Tab and change the maximum number of sets Save and close all done!
-
CSA 6.0 - policies in Audit mode - per groups
Hello,
Deploying CSA 6.0
Have several groups created but policies linked to these groups are the same.
I would like to have all of them work in Audit mode initially and move them
into non-Audit mode on per-group basis.
When I move policy out of Audit mode (uncheck box for specific policy) in group #1
I am getting messages that this policy will be not working in audit mode
in other groups as well because it is not in audit mode in group #1.
Is there way to work it around ?
and have policies be in Audit / non-Audit mode on per-group basis
thank you
AlexHi Tom
I agree, cloning rule modules is not an option.
But there would be no such thing as âaudit groupâ,
if I put policy in audit mode in one group (#1) and there is another group
where this policy is not in audit mode, then it becomes non-audit mode policy
even for group #1. This is what my experience tells me.
The ideal for our deployment (tens of groups, 1K users) would be able
to manipulate audit mode for policies on per-group basis.
Thanks
Alex -
Top n Analysis using correlated subquery
Please explain this query. It is doing top n analysis using correlated subquery. I need explaination of execution of this query.
Select distinct a.sal
From emp a
where 1=(select count ( distinct b.sal) from emp b
where a.sal <=b.sal)
Thanks in advanceTry breaking the query down and rewriting it in order to follow the logic;
SQL> --
SQL> -- Start by getting each salary from emp along with a count of all salaries in emp
SQL> --
SQL> select a.sal,
(select count (distinct b.sal) from scott.emp b ) count_sal
from scott.emp a
order by 1 desc
SAL COUNT_SAL
5000 12
3000 12
3000 12
2975 12
2850 12
2450 12
1600 12
1500 12
1300 12
1250 12
1250 12
1100 12
950 12
800 12
14 rows selected.
SQL> --
SQL> --Add a condition to the count for only salaries below or equal to the current salarySQL> --
SQL> select a.sal,
(select count (distinct b.sal) from scott.emp b where a.sal <=b.sal) rank_sal
from scott.emp a
order by 1 desc
SAL RANK_SAL
5000 1
3000 2
3000 2
2975 3
2850 4
2450 5
1600 6
1500 7
1300 8
1250 9
1250 9
1100 10
950 11
800 12
14 rows selected.
SQL> --
SQL> -- Add a condition to only pick the nth highest salary
SQL> --
SQL> select a.sal,
(select count (distinct b.sal) from scott.emp b where a.sal <=b.sal) rank_sal
from scott.emp a
where (select count (distinct b.sal) from scott.emp b where a.sal <=b.sal) = 4
SAL RANK_SAL
2850 4
1 row selected.Hope this helps. -
Top n analysis using hierarchial queries
hi all,
can we do top n analysis in hierarchial queries using level pseudo columns. if so please give an example.
thanks and regards,
sri ram.Hi,
Analytic functions (such as RANK) often interfere with CONNECT BY queries. Do one of them in a sub-query, and the other in a super-query, as shown below.
If you do the CONNECT BY first, use ROWNUM (which is assigned after ORDER SIBLINGS BY is applied) to preserve the order of the CONNECT BY query.
WITH connect_by_results AS
SELECT LPAD ( ' '
, 3 * (LEVEL - 1)
) || ename AS iname
, sal
, ROWNUM AS r_num
FROM scott.emp
START WITH mgr IS NULL
CONNECT BY mgr = PRIOR empno
ORDER SIBLINGS BY ename
SELECT iname
, sal
, RANK () OVER (ORDER BY sal DESC) AS sal_rank
FROM connect_by_results
ORDER BY r_num
;Output:
INAME SAL SAL_RANK
KING 5000 1
BLAKE 2850 5
ALLEN 1600 7
JAMES 950 13
MARTIN 1250 10
TURNER 1500 8
WARD 1250 10
CLARK 2450 6
MILLER 1300 9
JONES 2975 4
FORD 3000 2
SMITH 800 14
SCOTT 3000 2
ADAMS 1100 12
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the results you want from that data. If you use only commonly available tables (such as those in the scott or hr schemas), then you don't have to post any sample data; just post the results.
Explain how you get those results from that data.
Always say what version of oracle you're using. -
Whenever I open the editor in Photoshop Elements 12 it does not work. When I try to click open in the application it does not do anything. None of the buttons work. When I open a photo using file at the top it opens but I cannot edit it or use any of the features on the left side.
Hi Nealeh
Thanks i think I got it working of a fashion.
Except the replace colour, does not seem to end up with the colour I picked using the picker tool. Its as though it hads not replaced the colour but blended in the desired colour with the old incorrect colour!
Buy trial and error picking not the right colour but close - which when mixed with the existing colour is close.
Sorry I can't post the pictures as the Lingerie Mfg, has me under non disclosure.
The scenario is:- say a blonded mainly tanned model a high cut [at the hips] corsette style basque, with an ultra low bra line.
Our dear model, has just come back from St Barts with a fabulous Tan, and equally striking bold Tan lines!.
So we have great tanned legs, then the 'porcelain white band' where her swimsuit was.
Likewise we have a tanned face, and arms, shoulders etc and a great tan on the top of the cleavage, then it stops, white band to the top of the ultralow cut bra line of the basque.
She must have lived in like the most conservative bikini on the planet [50's style], for 2 weeks!
Had she had a normal skimpy bikini on, no problem!
If i don't solve it, she will get fired!
Not a lack of interest in your post, but I was out, and tried to log in to this site; which I could do, on my iPad Air / 5 [whatever its the new one]. And tried to 'sign in' - but it just hung at the
"Join Adobe Community" adobe sign in splash screen! with he little whell spinning around continuously!!!
I have Safari on this iPad. Guess that is all it runs.
So technology is not my friend today!
Maybe you are looking for
-
I need to encrypt user password with a key and store that key in the database along with the encrypted password. Every once in a while I need to generate a new encryption key. So far it works fine with the encryption/decryption routine for 3-4 tests,
-
The dot operator and a method called 'cons'?
I'm trying to write a static method that takes a list of things (array or List objects). It returns another list based on the first but changed by some rule. I am told that I have: non-static methods - head, tail, cons, isEmpty a static method - empt
-
TextField and CSS: How to control spacing between paragraphs
I'm using an external CSS to format a textField that has some HTML text in it, let's say something similar to this: myTextField.htmlText = "<p>paragraph one</p><p>paragraph two</p>"; How can I control the spacing between paragraphs when there is no s
-
While waiting at an airport, I downloaded a few apps for my iPhone. They worked long enough for me to confirm that the download was successful. I then came home, synced the iPhone via iTunes. The apps showed up as having been purchased, but now none
-
Is there any Utility industry company is using PP-production planning & exe
Dear All, Is there any Utility industry company is using PP-production planning & execution module and CO-PC product costing module ?? Meaning.. any Power generation/Transmission/distribution or water production/Transmission/distribution company is u