Use percentage function in pl sql
Hi,
I want to get the employees that their salary are in top 13% of salaries.
I learned in this forum that I can get the 10% of top salaries in HR schema by this query:
WITH got_tenth AS
SELECT last_name, salary
, NTILE (10) OVER (ORDER BY salary) AS tenth
FROM hr.employees
SELECT last_name, salary
FROM got_tenth
WHERE tenth = 10
ORDER BY salary DESC
;Output:
LAST_NAME SALARY
King 24000
Kochhar 17000
De Haan 17000
Russell 14000
Partners 13500
Hartstein 13000
Greenberg 12000
Errazuriz 12000
Higgins 12000
Ozer 11500There is no "TOP" keyword in Oracle.I wondered, 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).
Thanks a lot to helpers
CUME_DIST can help:
http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions035.htm
WITH tbl AS
SELECT last_name, salary
, cume_dist() OVER (ORDER BY salary DESC) AS cumulative_pcnt
FROM hr.employees
SELECT *
FROM tbl
WHERE cumulative_pcnt <=0.12;Tie values always evaluate to the same cumulative distribution value, so if you need exact 12% of the rows you can add employee_id in the ORDER BY list.
Edited by: 1006646 on 19.05.2013 10:14
Similar Messages
-
How to use percentage functions in BEx with structures
Hi, I need a help.
I have a query with a structure in the rows: two characteristics at left then the structure.
Plant, Year/Month and a structure with 3 lines (Line A = movement type = 1, 2, 3, Line B types 4, 5, 6, Line C types 7, 8, 9).
In the rows just a quantity.
I'm trying to use percentage functions CT or GT in the rows, but it's not working.
The idea is something like:
Plant 01 07/2010 Line A 30 30%
Line B 20 20%
Line C 50 50%
Result 33%
08/2010 Line A 40 20%
Line B 60 30%
Line C 100 50%
Result 66%.
When I do not use the structure percentage function works well, but with the structure results are completely wrong.
Any help will be appreciated.
César MenezesYou either have to use exception aggregation to give you the total per plant and use that in your percentage calculation, or you could define a formula in the cells. Here you can reference the specific cells you want to use as inputs.
-
Hello guys,
I'm writing a stored procedure which tries to convert a string representing a number to a fixed size number(with 2 positions fraction). For example, if the input was "15,456" the result would become 15.45.
I was able to aschieve this ussing the CAST function within a query as follows:
select cast ('15,456' as number(15,2)) from dual; -- (the comma in my case is configured as fraction separator). The previous query executes OK using a query analyzer like SQL Plus.
However, when I try to use the same function within a stored procedure, it will complain about the number's size (15,2) and wont compile.
v_importe_ingresado := CAST('15,456' AS NUMBER(15,2));
Error output: PLS-00103 found '(' but expected one of the following: .)@%
When removing the (15,2) it compiles ok
¿Any clue?
I will appreciate any help.
Thanks in advance,
Bernabé¿Any clue?¿¿¿Over complication???
SQL> select round(15.456, 2), trunc(15.456, 2) from dual
2 /
ROUND(15.456,2) TRUNC(15.456,2)
15.46 15.45
SQL> Cheers, APC
Blog : http://radiofreetooting.blogspot.com/ -
Missing results when using percentage function %GT
Hi all,
I'm using the percentage function in BEx. As you can see in the left two columns, it works fine when the results are higher then 0,4. All the results less than 0,4 are set to 0. In the last column I calculated the results with an Excel formula.
Any Idea, what the problem can be?
4.392,080 1,5635 % 1,563481163
997,440 0,0000 % 0,355066085
4.761,680 1,6951 % 1,695050405
1.260,000 0,4485 % 0,448531508
469,600 0,0000 % 0,167166981
280.916,720 100,0000 %
280.916,720 100,0000 %
Many thanks in advance!Dear Daya sagar,
Iam tried with taht functionality the query it self it is showing wrong and iam getting below error as result.
Diagnosis
The query contains a formula with the operator %RT. Therefore, the query cannot be released for OLE DB for OLAP.
The operators %GT, %RT, %CT, SUMGT, SUMRT, SUMCT and LEAF depend on the display of the list in the BEx Analyzer. If you used OLE DB for OLAP or MDX, this formula would deliver unexpected values.
Procedure
Do not release the query for OLE DB for OLAP, or do not use the operators %GT, %RT, %CT, SUMGT, SUMRT, SUMCT or LEAF. You may be able to achieve the desired result by selecting constants.
and report output is not coming.
Thanks & Regards,
Sathish -
Using max function in PL/SQL
VERY URGENT...
Am new to oracle...
I've written a package that display gif images in form of histogram/bar chart. using html,
I need to use max function to display values proportionately.
please help. i need to complete this assignment by 2/9/00 by 10.00 am at the latest. I've half written a function but I don't know if there's a simpler way fo doing this. html enabledFirst of all Thanks to all gentlemen who replied ..many thanks ...
Tried the ROW_NUMBER() option but still it is taking time...have given output for the query and tkprof results as well. Even when it doesn't fetch any record ( this is a valid cased because the input header id doesn't have any workflow request submitted & hence no entry in the wf_items table)..then also see the time it has taken.
Looked at the RANK & DENSE_RANK options which were suggested..but it is still taking time..
Any further suggestions or ideas as to how this could be resolved..
SELECT 'Y', 'Y', ITEM_KEY
FROM
( SELECT ITEM_KEY, ROW_NUMBER() OVER(ORDER BY BEGIN_DATE DESC) RN FROM
WF_ITEMS WHERE ITEM_TYPE = 'xxxxzzzz' AND ROOT_ACTIVITY = 'START_REQUESTS'
AND SUBSTR(ITEM_KEY,1,INSTR(ITEM_KEY,'-') - 1) = :B1
) T WHERE RN <= 1
call count cpu elapsed disk query current rows
Parse 0 0.00 0.00 0 0 0 0
Execute 1 0.00 1.57 0 0 0 0
Fetch 1 8700.00 544968.73 8180 8185 0 0
total 2 8700.00 544970.30 8180 8185 0 0
many thanks -
Need help in using sleep function in pl/sql
Hi,
need help:
I have a condition where i want to validate total_pass=total_fail and
I want to use the sleep function in a pl/sql where i want to wait for 2 minutes ie.checking
whether total_pass=total_fail based upon class_id .
I have the data in the table as:
CLASS_ID TOT_PASS TOT_FAIL
1 10 10
2 5 4
3 6 6
4 7 5
Any help will be needful for meI'm not quite sure what you are lookg for here, but whatever it is, your code as posted won't do it. You will never break out of the WHILE r_Class.Tot_Pass = r_Class.Tot_Fail loop, since these values will never change because you never get the next record form the cursor.
From your original data, it looks like your cursor will return multiple rows which implies to me that you want to fetch the first row from the cursor, check if tot_pass = tot_fail, if they are equal, sleep for two minutes then get the next row. This does not make sense to me. Once the select in the cursor is executed, the data it returns will not change due to Oracle's read consistency model, so there seems to me no point in the sleep.
The other alternative I can see is that you want to check all the returned rows, and if tot_pass = tot_fail for one of the rows (or possibly for all of the rows), then you want to sleep and try again.
If you can explain in words what it is you are trying to accomplish, someone will be able to point you to a solution.
John -
Not able to use a function inside a sql in a form, Why ??
Here SERIAL_NUM is a function, this sql work fine in TOAD and SQLPLUS but inside the form iam getting error saying "function serial_num cannot be used in a sql" Why is it like that ?? Is there anyother way to execute this sql ?
cursor c1 is
SELECT msn.ATTRIBUTE7 Order_No,
SERIAL_NUM(i.SERIAL_NUMBER) Serial_No,
msn.ATTRIBUTE5 Firmware,
msn.ATTRIBUTE15 Site_Pref
FROM atrd.INSTALLER_INFO i,
mtl_serial_numbers msn
where SERIAL_NUM(i.SERIAL_NUMBER)=msn.SERIAL_NUMBERHere is the process I did. My oim version is 9.1.0.2
1) Created java program in IBM RAD and compiled it.
2) Created jar file using jar -cvfm class-files command.
3) Copied the jar file to javatasks folder.
4) Tried to use this jar in adapter then got "Failed because null" and sometimes "Server could not load class" messages. most of the time i am getting "failed because null" message.
Compiled using javac command also without using this tool and created still no luck.... -
Using PowerShell Functions in t-SQL scripts
experts,
Can I use a power shell function that gets file size given file path by cross applying it to a table in SQL Server that holds file path of files?
fileID filepath
1 L:\DemoWebPages\About.cshtml.txt
2 L:\DemoWebPages\default.cshtml.txt.txt
3 L:\DemoWebPages\Layout.cshtml.txt
4 L:\DemoWebPages\Site.css.txt
if the above if the table in SQL Server, can I cross apply a power shell function that gets the file size when file path is passed from the table above?
Help Much Appreciated!
ebroMake sure that you are running on the machine where you've full permission to access file and
Sample data
create table filelist
fileid int,
path varchar(200))
insert into filelist values(1,'c:\Demystifying tempdb whitepaper.pdf')
insert into filelist values(2,'C:\Appleton Papers - 23 SQL DM - dani 6.28.13.pdf')
Powershell Scripts:-
Add-PSSnapin SqlServerProviderSnapin100 -ErrorAction silentlycontinue
Add-PSSnapin SqlServerCmdletSnapin100 -ErrorAction silentlycontinue
Function filesize
param([String] $path)
try {
if(Test-Path $path)
$size=(Get-Item $path).length/1024
write-host "$path size is $size KB"
catch [System.Exception] {
write-host "File not found"
$params = @{server='hqvd0026\kat';database='master'}
$Srv = invoke-sqlcmd @params -Query "SELECT * from dbo.filelist"
$srv
foreach ($db in $Srv)
filesize -path $db.path -
Using NVL function in Dynamic SQL
Hi ,
I have created a procedure using the Dynamic SqL and while using the NVL() getting the following error . ORA-00936: missing expression.
The query I have written as
SQL_Txt:=' INSERT INTO VF.tblCData (A, B, C, D, E, F,G,H,I,J)
SELECT '||l_A||',
'||l_B||',
'||l_C||',
'||l_D||',
NULL ,
'||L_F||',
NVL('||Param1||',''''),
NVL('||Param2||',''''),
NVL('||Param3||',''''),
NULL
FROM '||ParamTbl1||' WHERE ' ;
and so on.
For Param1 I have data for one execution and Param2 and Param3 is null for that execution.
While executing the same I am getting below
INSERT INTO VF.tblCData (A, B, C, D, E, F,G,H,I,J)
SELECT 25,
1,
7,
6,
NULL ,
5,
NVL(PurchaseDate,''),
NVL(,''),
NVL(,''),
NULL
FROM xyz.PBuyer@pocdb WHERE
and error ORA-00936: missing expression is popping up for Param2 and Param3 NVL(,'')
Any suggestion to resolve this issue is highly appreciable.
Thanks
SudiptaNVL(,''),Where's the first argument to NVL? That's the obvious problem. Empty strings are NULL in Oracle anyway, so just lose the NVL and insert the values...
C:\>
C:\>sqlplus hr/hr
SQL*Plus: Release 11.2.0.3.0 Production on Wed May 8 10:08:53 2013
Copyright (c) 1982, 2011, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> set NULL I_AM_NULL
SQL> create table x(y varchar2(20));
Table created.
SQL> insert into x values ('');
1 row created.
SQL> select * from x;
Y
I_AM_NULL
SQL> -
How to use document() function in PL/SQL XSLT parser ?
The "XDB Developers Guide" documentation says on page 12-18
>
The application can use DBUriType objects:
To make references, such as import or include, to related XSL stylesheets. You can encode these references within the XSL stylesheet itself.
following this i added string like this to my stylesheet
<xsl:apply-templates select="document('/ORADB/SCOTT/STYLESHEET_TAB/ROW[ID=1]/STYLESHEET/text()')" mode="include"/>
<xsl:cinclude href="/ORADB/SCOTT/STYLESHEET_TAB/ROW[ID=1]/STYLESHEET/text()"/>
But when XSLT processor reaches this, it fails.
I also even tried like this
<xsl:include href="/ORADB/SCOTT/STYLESHEET_TAB/ROW[ID=1]/STYLESHEET/text()"/>
but result is the same ;(((
Generally - is there ANY way XSLT processor can deal with stylesheet which contains
DBURI references to another stylesheets stored in XMLTYPE columns ?
I'm currently in charge to develop a content management system for a huge corporate site,
so i'm VERY interested to know - does this feature really exists on Oracle 9.2 ?
Please ansver ASAP.BTW: following this link
xsl:include within XSL stylesheet stored in XMLType column
i've encountered that this theme has been asked but none from Oracle staff has answered on it yet ;((((((( -
Performance issue with using MAX function in pl/sql
Hello All,
We are having a performance issue with the below logic wherein MAX is being used in order to get the latest instance/record for a given input variable ( p_in_header_id).. the item_key is having the format as :
p_in_header_id - <number generated from a sequence>
This query to fetch even 1 record takes around 1 minutes 30 sec..could someone please help if there is a better way to form this logic & to improve performance in this case.
We want to get the latest record for the item_key ( this we are getting using MAX (begin_date)) for a given p_in_header_id value.
Query 1 :
SELECT item_key FROM wf_items WHERE item_type = 'xxxxzzzz'
AND SUBSTR (item_key, 1, INSTR (item_key, '-') - 1) =p_in_header_id
AND root_activity ='START_REQUESTS'
AND begin_date =
(SELECT MAX (begin_date) FROM wf_items WHERE item_type = 'xxxxzzzz'
AND root_activity ='START_REQUESTS'
AND SUBSTR (item_key, 1, INSTR (item_key, '-') - 1) =p_in_header_id);
Could someone please help us with this performance issue..we are really stuck because of this
regardsFirst of all Thanks to all gentlemen who replied ..many thanks ...
Tried the ROW_NUMBER() option but still it is taking time...have given output for the query and tkprof results as well. Even when it doesn't fetch any record ( this is a valid cased because the input header id doesn't have any workflow request submitted & hence no entry in the wf_items table)..then also see the time it has taken.
Looked at the RANK & DENSE_RANK options which were suggested..but it is still taking time..
Any further suggestions or ideas as to how this could be resolved..
SELECT 'Y', 'Y', ITEM_KEY
FROM
( SELECT ITEM_KEY, ROW_NUMBER() OVER(ORDER BY BEGIN_DATE DESC) RN FROM
WF_ITEMS WHERE ITEM_TYPE = 'xxxxzzzz' AND ROOT_ACTIVITY = 'START_REQUESTS'
AND SUBSTR(ITEM_KEY,1,INSTR(ITEM_KEY,'-') - 1) = :B1
) T WHERE RN <= 1
call count cpu elapsed disk query current rows
Parse 0 0.00 0.00 0 0 0 0
Execute 1 0.00 1.57 0 0 0 0
Fetch 1 8700.00 544968.73 8180 8185 0 0
total 2 8700.00 544970.30 8180 8185 0 0
many thanks -
WITHOUT USING ROW_NUMBER FUNCTIONS IN T-SQL
INPUT:-
CUST_ID
GIFT_ID
100
10
100
20
100
30
200
10
200
20
200
30
300
20
OUTPUT:-
CUST_ID
GIFT_ID
SEQ
100
10
1
100
20
2
100
30
3
200
10
1
200
20
2
200
30
3
300
20
1
santoshbangaloreTHANK YOU SO MUCH FOR YOUR ANS? BUT MY INPUT TABLE A CONTAIN ONLY TWO COLUMN'S
CUST_ID,GIFT_ID
AND IN OUT PUT I NEED THE ABOVE OUTPUT WITH
CUST_ID,GIFT_ID,ROW_NUMBER AS SHOWN ABOVE?
santoshbangalore -
Using cursor function in sql statement
hi all
can anyone plss explain why and when we will use cursor function in a sql statement like this and what is the difference while executing this sql statement with cursor function in comparison of a simple sql statement----
select
department_name,
cursor (
select last_name
from employees e
where e.department_id = d.department_id
order by last_name
) the_employees
from departments d
thnx in advanceRTFM
http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/sqloperations.htm#sthref1452
Cheers
Sarma. -
How to use db2 function in the HQL
hello
i am newbie to hibernate, now i am choosing a solution for my project, in this project, it use db2 function in the sql clause as follow:
insert into idstool.access(userid,node,password) values('userid','nodename',encrypt('password','nodename'));
i wonder if i can implement such function by using hibernate, that is if hibrenate can use the db2 function, or user-defined sql functions? if yes, how?
thanks for any helpsI think you'll find that you can do this through HQL. You also have the option of invoking a stored procedure or invoking native SQL in tandem with the normal Hibernate options.
-
I have a table with this records:
linknumber history
110 46,57,89
220
50
330 22
440 10,12
I want to have this result:
rownumber linknumber
history
1 110 46
2 110 57
3 110 89
4 220 50
5 330 22
6 440
10
7 440 12
and I have this function for split(camma):
ALTER FUNCTION
[dbo].[Split](@String varchar(8000), @Delimiter char(1))
returns @temptable
TABLE (items varchar(8000))
as
begin
declare @idx int
declare
@slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String
is null return
while @idx!= 0
begin
set @idx =
charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx
- 1)
else
set @slice = @String
if(len(@slice)>0)
insert
into @temptable(Items) values(@slice)
set @String =
right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
but I don,t know how to use this function in T-sql for
my favorir result?plaese guide me how do I do this?thanks>> I have a table with this records [sic]: <<
Rows are not records; this is a basic concept in RDBMS. Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming
conventions and formatting rules. Temporal data should use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums.
The term “link” is not RDBMS, either. It comes from pointer chains and linked lists. RDBMS has no pointers or lists! It looks like you have no idea what you are doing.
Non-RDBMS programmers violate 1NF and write those absurd string splitters. In fact, you did not do a good job of writing bad code. You posted a BASIC or FORTRAN program written with 1970's T-SQL. You even used != instead of SQL's <> !
Passing a list of parameters to a stored procedure can be done by putting them into a string with a separator. I like to use the traditional comma. Let's assume that you have a whole table full of such parameter lists:
CREATE TABLE InputStrings
(keycol CHAR(10) NOT NULL PRIMARY KEY,
input_string VARCHAR(255) NOT NULL);
INSERT INTO InputStrings
VALUES ('first', '12,34,567,896'),
('second', '312,534,997,896'),
etc.
This will be the table that gets the outputs, in the form of the original key column and one parameter per row.
It makes life easier if the lists in the input strings start and end with a comma. You will need a table of sequential numbers -- a standard SQL programming trick, Now, the query,
CREATE VIEW ParmList (keycol, place, parm)
AS
SELECT keycol,
COUNT(S2.seq), -- reverse order
CAST (SUBSTRING (I1.input_string
FROM S1.seq
FOR MIN(S2.seq) - S1.seq -1)
AS INTEGER)
FROM InputStrings AS I1, Series AS S1, Series AS S2
WHERE SUBSTRING (',' + I1.input_string + ',', S1.seq, 1) = ','
AND SUBSTRING (',' + I1.input_string + ',', S2.seq, 1) = ','
AND S1.seq < S2.seq
GROUP BY I1.keycol, I1.input_string, S1.seq;
The S1 and S2 copies of Series are used to locate bracketing pairs of commas, and the entire set of substrings located between them is extracted and cast as integers in one non-procedural step. The trick is to be sure that the right hand comma of the bracketing
pair is the closest one to the first comma. The relative position of each element in the list is given by the value of "place", but it does a count down so you can plan horizontal placement in columns.
This might be faster now:
WITH Commas(keycol, comma_seq, comma_place)
AS
(SELECT I1.keycol, S1.seq,
ROW_NUMBER() OVER (PARTITION BY I1.keycol ORDER BY S1.seq)
FROM InputStrings AS I1, Series AS S1
WHERE SUBSTRING (',' + I1.input_string + ','
FROM S1.seq
FOR 1) = ','
AND S1.seq <= CHARLENGTH (I1.input_string))
SELECT SUBSTRING(',' + I1.input_string + ','
FROM C1.comma_place +1
FOR C2.comma_place - C1.comma_place - 1)
FROM Commas AS C1, Commas AS C2
WHERE C2.comma_seq = C1.comma_seq + 1
AND C1.keycol = C2.keycol;
The idea is to get all the positions of the commas in the CTE and then use (n, n+1) pairs of positions to locate substrings. The hope is that the ROW_NUMBER() is faster than the GROUP BY in the first attempt. Since it is materialized before the body of the
query (in theory), there are opportunities for parallelism indexing and other things to speed up the works.
Hey, I can write kludges with the best of them, but I don't. You need to at the very least write a routine to clean out blanks, handle double commas and non-numerics in the strings, take care of floating point and decimal notation, etc. Basically, you must
write part of a compiler in SQL. Yeeeech! Or decide that you do not want to have data integrity, which is what most Newbies do in practice altho they do not know it.
>> but I do not know how to use this function in T-SQL for my favored result? Please guide me how do I do this? <<
Stop programming until you learn SQL.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL
Maybe you are looking for
-
Hi all, I just made this observation and wanted to share it with all you guys. From SAP BASIS Release 700, the SAP Logon password field has become 12 characters in length. Moreover, it is now case sensitive. If you go to transaction SU01 in the chang
-
SYSTEM TEMPERATUR​E 90D .
help me . ASAP! i have a compaq presario CQ42 . today i has disassembling my laptop and applying thermal paste on cpu and gpu . so , the problem is when i play games about 5min or 10min my laptop suddenly go on sleep and shutdown itself then i try to
-
Hi We will use open dataset <dataset name> input/ output in text mode encoading default. Can anyone tell me we will write INPUT or OUTPUT what is meaning of that. What is INPUT for & what is OUTPUT FOR?
-
":1", ":2" variable refs in SQL on wire
I'm writing a tool to analyze Oracle SQL queries over the network and I've found out that some of the numerical variables being sent over the network are encoded with ":1", ":2" refernces, e.g.: SELECT * FROM table WHERE x = :1 AND y = :2 Then :1 and
-
An error occurred while attempting to change modules while starting up LR 4.1. New install on a new MBP first time trying to start up