Select top 10 percentage
Hi,
I want to get the top 10% of salaries in employees table. But I got error:
SQL> select top 10 percent salary
2 from employees
3 order by salary desc;
ORA-00923: FROM keyword not found where expectedHow can I get the top 10% percent?
Thanks a lot
Hi,
998093 wrote:
... What if I want to get, for example, the employees who are in the top 12% of the salaries? here we cannot use deciles (maybe we can but it won't be very nice).Actually, you can. How nice it will be depends on your data and your exact requirements.
Earlier, we said that the top 10% was the 10th of 10 buckets.
We could say that the top 12% is the last 12 of 100 buckets:
WITH got_tenth AS
SELECT last_name, salary
, NTILE (100) OVER (ORDER BY salary) AS hundredth
FROM hr.employees
SELECT last_name, salary
FROM got_tenth
WHERE hundredth > 100 - 12
ORDER BY salary DESC
;I won't clutter up this message by showing the results for every query; I'll just report the total number of rows. The query I posted earlier (for the top 10%) produced 10 rows of output; the query immediately above produces 12. That's starting to bother me. There are 107 rows in hr.employees. (They all have a salary; don't forget to deal with NULLs in general.) The top 10% should contain 107 * .1 = 10.7 rows. Of course, this has to be rounded to an integer, so it would have been a little better if the top 10% showed 11 rows (since 11 is closer to 10.7 than 10 is), but it's not a real big problem. Likewise, the top 12% should have 107 * .12 = 12.84 rows, so 13 rows of output might be better, but 12 rows isn't too bad.
Now say we want to simplify the condition "WHERE hundredth > 100 - 12". Instead of taking the last 12 buckets in ascending order, let's take the first 12 buckets in descending order:
WITH got_tenth AS
SELECT last_name, salary
, NTILE (100) OVER (ORDER BY salary DESC) AS hundredth
FROM hr.employees
SELECT last_name, salary
FROM got_tenth
WHERE hundredth <= 12
ORDER BY salary DESC
;The result set now contains 19 rows! Why? Because NTILE puts extra items (when there are extras) in the lower-numbered buckets. When there were 10 buckets, then buckets 1 trough 7 had 11 items each, and buckets 8 through 10 had 10 items. We were only dispolaying bucket #10, so we only saw 10 items. Now that there are 100 buckets, buckets 1 through 7 will have 2 items each, and buckets 8 through 100 will have 1 item each. When we numbered the buckets in ascending order, and took the last 12 buckets, we wound up with 12 * 1 = 12 rows, but when we numbered the buckets in descending order and took the first 12 buckets, we got (7 * 2) + (5 * 1) = 19 rows.
When you have R rows and B buckets, and R/B doesn't happen to be an integer, then NTILE will distribute the rows as equally as possible, but some rows will have 1 item more than others. When the ratio R/B is high, that might not be very significant, but when R/B gets close to 1, then you have situations like the one above, where the bigger buckets, although they have only 1 more item than the smaller buckets, are twice as big. Even worse is the situation where R/B is less than 1; then the last buckets will have 0 items.
So, as you noticed, NTILE isn't a good solution for all occasions. Here's a more accurate way, using the analytic ROW_NUMBER and COUNT functions:
WITH got_analytics AS
SELECT last_name, salary
, ROW_NUMBER () OVER (ORDER BY salary DESC) AS r_num
, COUNT (*) OVER () AS n_rows
FROM hr.employees
SELECT last_name, salary
FROM got_analytics
WHERE r_num / n_rows <= 12 / 100
ORDER BY salary DESC
;This produces 12 rows.
If you want 13 rows (because 107 * .12 = 12.84 is closer to 13), then you can change the main WHERE clause like this:
WITH got_analytics AS
SELECT last_name, salary
, ROW_NUMBER () OVER (ORDER BY salary DESC) AS r_num
, COUNT (*) OVER () AS n_rows
FROM hr.employees
SELECT last_name, salary
FROM got_analytics
WHERE r_num <= ROUND (n_rows * 12 / 100)
ORDER BY salary DESC
;
Similar Messages
-
Oracle 10g Select Top 100 Percent
Hello
How to convert MS sql 2008 select top 100 query Oracle PL/SQL ? MY sample MSSQL select query
SELECT TOP (100) PERCENT dbo.Operations.OpID, dbo.CompanyInfo.Name AS CompanyName, dbo.CustomerInfo.SubscriberNo, dbo.CustomerInfo.FirstName,
dbo.CustomerInfo.LastName, dbo.Operations.OpDate, dbo.Operations.BillCount, dbo.Operations.TotalAcceptedCash, dbo.Operations.KioskID,
dbo.Operations.ReceiptNo, dbo.Operations.KioskOpID, dbo.KioskInfo.Name AS KioskName, dbo.Operations.TotalBill, dbo.Operations.TotalPayBack,
dbo.CompanyInfo.CompanyID, dbo.Operations.ConfirmedRecord, dbo.PayMethod.ACK AS PayMethod
FROM dbo.Operations INNER JOIN
dbo.CustomerInfo ON dbo.Operations.SubscriberNo = dbo.CustomerInfo.SubscriberNo INNER JOIN
dbo.CompanyInfo ON dbo.Operations.CompanyID = dbo.CompanyInfo.CompanyID INNER JOIN
dbo.KioskInfo ON dbo.Operations.KioskID = dbo.KioskInfo.KioskID INNER JOIN
dbo.PayMethod ON dbo.Operations.PayMethodID = dbo.PayMethod.PayMethodID
ORDER BY dbo.Operations.OpDate DESCHi,
Please read SQL and PL/SQL FAQ
Additionally when you put some code please enclose it between two lines starting with {noformat}{noformat}
i.e.:
{noformat}{noformat}
SELECT ...
{noformat}{noformat}
From what I have found on MS SQL documentation it seems that TOP keyword limits the output to a specified percentage of total number of rows. In your case, having specified 100, you are returning 100% of rows.
So you can simply remove *TOP (100) PERCENT*
Regards.
Al -
Hi When i create the downpayment process in the invoice i get amount as value but my requirement is in percentage even after i select the percentage basis milestone billing please help what can be done
downpayment percentage , so if i want 50 percent of order value to be paid and when i go to faz type the invoice is created for 0 value that 50 percent of the amount is not getting calculated , where as when i enter in order same as 50 percent in amount it gets calculated in invoice, any help ?
-
How to select top one in CDS view ?
I have tried following logic to select top one in CDS view but its giving error -
define view Cds_View_First_Reference as select top one CReferredObject from CDSVIEWCROSSREFHi Ruchi,
since you posted this question in "ABAP in Eclipse" I assume you are asking about CDS in ABAP. This is important because the CDS features sets in ABAP and (native) HANA are different.
Be that as it may,, SELECT TOP 1 is neither supported in the CDS implementation in ABAP nor in HANA.
In ABAP you might consider using the min() or max() function together with the appropriate GROUP BY clause in the CDS view (depending on what you want to achieve), but you can also easily "implement" this in the Open SQL statement which selects from your CDS view.
Using the additions SELECT SINGLE or UP TO 1 ROWS and an appropriate ORDER BY clause in Open SQL, you can achieve the same as SELECT TOP 1.
Unfortunately there is currently no possibility to define a view which delivers the TOP 1 which you can again use in another view ("view on view").
Kind regards
Chris -
Prepared Statement, executing SELECT TOP in Ms Access
I'm having the following problem. I built an application fetching data without any problem from MS SQL Server, this was using prepared statements. Now i'm having this strange problem with the following query:
SELECT TOP 1 *
FROM table
WHERE appliance_id = ?
AND ttimestamp_initpk <= ?
AND ((Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?) OR (Type = ?))
ORDER BY ttimestamp_initpk DESC
While on SQL Server this fetches just a record, on MS Access it fetches the whole set of records without worrying about TOP instruction.
That is, it acts like a SELECT * FROM, and this slows down runtime behaviour.
I'm using sun.jdbc.odbc.JdbcOdbcDriver, is it the problem?
Thanks, MirkoThanks for your answer, but i'm not sure this is the reason.
I made one more test: i wrote a .Net application connecting to a MS Access using an ODBC connection. SELECT TOP statement is working fine, so i think i'll try another JDBC driver. Any other solution??
Thanks,
Mirko -
ALTERNATIVE FOR 'SELECT TOP STATEMENT
HI FRIENDS
IF ANY ONE KNOWS HOW TO CONVERT THE SQL STATEMENT GIVEN BELOW PLEASE HELP ME
SELECT TOP 1 CardID FROM EasyRechargeMaster WHERE CardGroup = EasyRecharge.CardGroup
THANKS & REGARDSCheck this query. It should give you desired results....Are you sure about that? Does TOP 1 mean "whatever happens to be the first row fetched"?
-
Hi,
Can somebody give me the HANA equivalent of the following SQL query:
SELECT TOP (731-624+1) COLUMNNAME FROM TABLENAME
In case of HANA, it gives syntax error near "(".Hi Yash,
As per the HANA SQL syntax supported case is
<select_clause> ::= SELECT [TOP <unsigned_integer>] [ ALL | DISTINCT ]
<select_list>
After Top only an unsigned intger is expected and cannot handle an <expression> like in your example.
Hope this is useful.
Best Regards,
Ranjit -
SELECT TOP 1 .... ORDER BY
Hi,
I have the following statement in SQL SERVER:
SELECT TOP 1 NAME FROM STUDENT ORDER BYGRADE
Now, I am trying to translate it ti ORACLE PLSQL, I came up with this statement:
SELECT NAME FROM STUDENT WHERE ROWNUM=1 ORDER BY GRADE
It doesn't work. I guess ORACLE generates ROWNUM before the ORDER BY operation...
How can I have SELECT TOP N ... ORDER BY ... in Oracle the way that I have it in SQL server?
Any help would be apprecited,
AlanCan you cut and paste exactly what you're doing in a SQL*Plus session? It seems to work for me
SCOTT @ hp92 Local> create table t as select * from all_objects;
Table created.
Elapsed: 00:00:08.40
SCOTT @ hp92 Local> desc t;
Name Null? Type
OWNER NOT NULL VARCHAR2(30)
OBJECT_NAME NOT NULL VARCHAR2(30)
SUBOBJECT_NAME VARCHAR2(30)
OBJECT_ID NOT NULL NUMBER
DATA_OBJECT_ID NUMBER
OBJECT_TYPE VARCHAR2(18)
CREATED NOT NULL DATE
LAST_DDL_TIME NOT NULL DATE
TIMESTAMP VARCHAR2(19)
STATUS VARCHAR2(7)
TEMPORARY VARCHAR2(1)
GENERATED VARCHAR2(1)
SECONDARY VARCHAR2(1)
SCOTT @ hp92 Local> create index idx_t on t( object_id );
Index created.
Elapsed: 00:00:00.78
SCOTT @ hp92 Local> analyze table t compute statistics for all indexed columns;
Table analyzed.
Elapsed: 00:00:00.53
SCOTT @ hp92 Local> set autotrace on;
SCOTT @ hp92 Local> select *
2 from (select * from t order by object_id)
3 where rownum < 2;
OWNER OBJECT_NAME SUBOBJECT_NAME
OBJECT_ID DATA_OBJECT_ID OBJECT_TYPE CREATED LAST_DDL_ TIMESTAMP STATUS T G S
SYS DUAL
222 222 TABLE 12-MAY-02 12-MAY-02 2002-05-12:16:20:50 VALID N N N
Elapsed: 00:00:00.13
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 COUNT (STOPKEY)
2 1 VIEW
3 2 TABLE ACCESS (BY INDEX ROWID) OF 'T'
4 3 INDEX (FULL SCAN) OF 'IDX_T' (NON-UNIQUE)
Statistics
0 recursive calls
0 db block gets
3 consistent gets
1 physical reads
0 redo size
1142 bytes sent via SQL*Net to client
511 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
1 rows processedJustin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC -
Looking for the oracle equivalent of T-SQL 'SELECT TOP n'
Hi,
I'm looking for the Oracle equivalent of T-SQL 'SELECT TOP n'
and can't find any. There is SAMPLE(n) function but it supposed
to pick up random values and I'm not sure if it's possible to
make it select top values. Please help 8-)
ThanxHi Marina.
Oracle does not have a functionality like SQL Server for TOP
selection. The ROWNUM option should be used with great care and
you may get unreliable results.
Try looking at Metalink
Doc ID: 291065.999
Doc ID: 267329.999
- They discuss this issue, and solutions. -
Hi Guys,
I tried Group By from Select Top 1 Records, As below the script wasn't work.
Please help.
SELECT TOP 1 NR.SHGId, NR.Amount
FROM NEW_DCB_REPORT NR
WHERE NR.SHGId = ND.SHGId
AND NR.ShgMemberId = ND.ShgMemberId
AND NR.LoanNumber = ND.LoanNumber
GROUP BY NR.SHGId,NR.Amount
ORDER BY NR.LedgerNumber DESC
SHGId
SHGMemberId
LoanNumber
Amount
Select Top 1 Row
1028
147852
1
1000
Select Top 1 Row
1028
147853
1
2000
Select Top 1 Row
1028
147854
1
1000
Select Top 1 Row
1028
147855
1
1000
5000
I expected the results are:
SHGId
Amount
1028
5000Yes I did it.
Select SHGId,
SUM(Amount)
amt FROM
SELECT NR.SHGId,
NR.Amount,
, Row_number()
Over(partition
by NR.SHGId,
NR.ShgMemberId , NR.LoanNumber
Order
by NR.LedgerNumber
DESC
) rn
FROM NEW_DCB_REPORT NR
JOIN
NEW_DCB_REPORT ND
ON
NR.SHGId
=
ND.SHGId
AND NR.ShgMemberId
= ND.ShgMemberId
AND NR.LoanNumber
= ND.LoanNumber
) t
Where rn=1
GROUP
BY SHGId
I just changed above the script Partition by add one more column and
[yourNDTable]
Should come NEW_DCB_REPORT table.
However, It shows below the error ,. Please help.
Invalid object name 'NEW_DCB_REPORT'. -
select * from tablename ------always running,but get nothing
select top 1 * from tablename -------get result quickly
select top 2 * from tablename -------get result quickly
select top 14259 * from tablename --------get result quickly
select top 14260 * from tablename --------always running,but get nothing
the thread is:
java.net.SocketInputStream.socketRead0(Native Method)
java.net.SocketInputStream.read(SocketInputStream.java:150)
java.net.SocketInputStream.read(SocketInputStream.java:121)
com.microsoft.sqlserver.jdbc.TDSChannel.read(IOBuffer.java:1782)
com.microsoft.sqlserver.jdbc.TDSReader.readPacket(IOBuffer.java:4838)
- 已锁定com.microsoft.sqlserver.jdbc.TDSReader@54269910
com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6150)
com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:402)
com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
- 已锁定java.lang.Object@320b1499
com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.execute(SQLServerPreparedStatement.java:332)when I run the below sql of Uri Dimant,I get many rows,I think you are right!
Do you have some method to handle this problem?
Or do you have some information for me to Learn?
Thanks a lot.
SELECT
owt.session_id AS waiting_session_id,
owt.blocking_session_id,
DB_NAME(tls.resource_database_id) AS database_name,
(SELECT SUBSTRING(est.[text], ers.statement_start_offset/2
+ 1,
(CASE WHEN ers.statement_end_offset = -1
THEN LEN(CONVERT(nvarchar(max), est.[text])) * 2
ELSE ers.statement_end_offset
END
- ers.statement_start_offset
) / 2)
FROM sys.dm_exec_sql_text(ers.[sql_handle]) AS est) AS waiting_query_text,
CASE WHEN owt.blocking_session_id > 0
THEN (
SELECT
est.[text] FROM sys.sysprocesses AS sp
CROSS APPLY sys.dm_exec_sql_text(sp.[sql_handle]) as est
WHERE sp.spid = owt.blocking_session_id)
ELSE
NULL
END AS blocking_query_text,
(CASE tls.resource_type
WHEN 'OBJECT' THEN OBJECT_NAME(tls.resource_associated_entity_id, tls.resource_database_id)
WHEN 'DATABASE' THEN DB_NAME(tls.resource_database_id)
ELSE (SELECT OBJECT_NAME(pat.[object_id], tls.resource_database_id)
FROM sys.partitions pat WHERE pat.hobt_id = tls.resource_associated_entity_id)
END
) AS object_name,
owt.wait_duration_ms,
owt.waiting_task_address,
owt.wait_type,
tls.resource_associated_entity_id,
tls.resource_description AS local_resource_description,
tls.resource_type,
tls.request_mode,
tls.request_type,
tls.request_session_id,
owt.resource_description AS blocking_resource_description,
qp.query_plan AS waiting_query_plan
FROM sys.dm_tran_locks AS tls
INNER JOIN sys.dm_os_waiting_tasks owt ON tls.lock_owner_address = owt.resource_address
INNER JOIN sys.dm_exec_requests ers ON tls.request_request_id = ers.request_id
AND owt.session_id = ers.session_id
OUTER APPLY sys.dm_exec_query_plan(ers.[plan_handle]) AS qp
GO -
Can SELECT TOP have argument?
Newbie’s question, I believe.
I wanted to make a stored procedure to returns last several rows or last several hundred rows depending on the situation, so I started writing queries in order to copy/paste them into procedure. There are two queries, first works, but
second one shows syntax error in select statement. Can anyone tell me why, and how to go around this?
SELECT TOP 5 * FROM Table1 ORDER BY ID DESC
DECLARE @Counter as int
SET @ Counter = 5
SELECT TOP @ Counter FROM Table1 ORDER BY ID DESCThis works. But I still don?t realize what was wrong with my syntax. Do those () will convert what?s inside parameter to string so parser could read it correctly? What actually is going on here?
It's just the way it is. Originally there was only SELECT TOP n, where the value after TOP had to be a constant. Then they added the ability to have expression, but then they added the parens. This is so that you can say things like:
SELECT TOP (SELECT ... FROM ...) ... FROM
if you feel like.
The old syntax is deprecated but remains for compatibility reasons.
Erland Sommarskog, SQL Server MVP, [email protected] -
Select Top 10 when it includes a GroupBy
I frequently use Select Top 10... to test a query before running it on a large MSSQL database. Works fine, except when the query includes a Group By Clause when it then seems to take as long as not using Top 10. I suspect this is beause it is actually
reading the whole table to get the top 10 Group Bys, whereas all I wanted was for it read the first 10 records and Group the result. Is there a way to write so that it does that
Gerry Mescalsample code ..modify and try this SELECT a.*
FROM
SELECT a.*, ROW_NUMBER() OVER(PARTITION BY m.[col1] ORDER BY m.[col2] DESC) an
FROM [table] a
) a
WHERE a.an <= 10
ORDER BY m.[col2] DESCmark as answer if it is useful -
Update with Select top n statement
Hi All,
Can I use update statemet like this..
Update table1
set Name=(select top (100) t2.name from table2 t2 where table1.ID=t2.ID)
Please let me know ASAP its very urgent
Thanks in Advance
RH
sqlHi sql9 !
You might need below query;
CREATE TABLE Table1 (ID INT,Name VARCHAR(10))
CREATE TABLE Table2 (ID INT,Name VARCHAR(10))
--TRUNCATE TABLE Table1
--TRUNCATE TABLE Table2
INSERT INTO Table1
SELECT 1,'ABC' UNION ALL
SELECT 2,'DEF' UNION ALL
SELECT 3,'GHI'
INSERT INTO Table2
SELECT 1,'JKL' UNION ALL
SELECT 1,'MNO' UNION ALL
SELECT 2,'PQR' UNION ALL
SELECT 2,'STU' UNION ALL
SELECT 3,'VWX' UNION ALL
SELECT 3,'YZ'
UPDATE Table1 SET Name = (SELECT TOP 1 T2.Name FROM Table2 T2 WHERE Table1.ID = T2.ID)
SELECT * FROM Table1
--ID Name
--1 JKL
--2 PQR
--3 VWX
--You can simply re-write your SQL with below query and you don't have to specify TOP Clause inside subquery
UPDATE T1 SET T1.Name = T2.Name
FROM Table1 T1
INNER JOIN Table2 T2 ON T2.ID = T1.ID
SELECT * FROM Table1
--ID Name
--1 JKL
--2 PQR
--3 VWX
Note : In your first query TOP 100 returning more than 1 value from subquery which is not allowed.
Please let me know if this doesn’t work for you. Hope I have answered you correctly.
Thanks,
Hasham -
Hello,
I was wondering if it was possible to limit the amount of lines selected from a table.
I tried select top n, as it works in SQL, but SAP doesn 't support this syntax..
Is this doesn't work, is there any other way to limit the amount of data selected ?Hi,
Use select upto n rows
Select * from MARA into table ITAB UPTO 10 rows.
select top 10 rows in table.
Regards
SAB
Maybe you are looking for
-
ITunes LP - How can I return to the LP content while playing?
The other day I bought an iTunes LP (Pink Floyd - The Wall) which contains quite a lot of nice extra material. My problem is that to access that content you must start playing the album from the top, even if it's already playing. What I do is that I
-
I use an old MBP with ver. 10.8.6. I cannot upgrade any more, which is fine for now. I downloaded FX Factory and Noise Industires Manifesto as a trail. I went on my business. Never really using them. I find now that when I startup FC both programs wa
-
Yahoo mail ,using ff shows resolutions not high enough but works withchrome
When I log into Yahoo mail I get a popup stating my computer resolutions are too low. Nothing has changed. I can log in OK using Chrome.or Google on this same computer.
-
I got a new PC. & my itunes is working fine on it, but I can't seem to upload any of the new songs that I have downloaded on iTunes on my new PC to my iPod..
-
Script Logic using when Condition
Hi, Im working on BPC 7.5 SP04 MS and I cant figure out how to make this logic work: 1. Cuenta members (account) with the ivaacred property, are multiplied by a certain value and stored in the account 13010A *WHEN TIEMPO *IS 2009.Jan, etc etc.....