PL/SQL--How to calculate a median using PL/SQL

How would I calculate a median, not an average, using PL/SQL? Thanks.

1. The MEDIAN value is the value of the item in the middle of a data set.
2. For a dataset with 5 rows (sorted by the value) it is the value in row 3; for any ODD number of rows n use row number 'TRUNC(n/2) + 1'.
3. For a dataset with 6 rows the average of the two middle rows (rows 3 and 4) is usually used; for any EVEN number of rows n use row numbers 'TRUNC(n/2)' and 'TRUNC(n/2) + 1'.
4. Check for the special case where there are no rows in the result set first.
Using pseudo-code it might look like:
SELECT COUNT(1) INTO num_rows FROM mytable;
IF num_rows = 0 THEN
RETURN 0;
END IF;
first_row := TRUNC(num_rows/2);
-- set 2nd row to be same as first if ODD number of rows
second_row := first_row;
IF first_row * 2 = num_rows THEN
-- set 2nd row to be row after 1st if EVEN number of rows
second_row := second_row + 1;
END IF;
-- query the average needed. Note that for an ODD number of rows this still works.
SELECT avg(myvalue) FROM (SELECT ROWNUM rnum, rvalue FROM (SELECT myvalue rvalue FROM mytable ORDER BY myvalue))
WHERE rnum BETWEEN first_row AND second_row;
END IF;
I suggest you write and test the innermost query above first (SELECT myvalue rvalue FROM MYTABLE ORDER BY myvalue).
Then use it as a subquery for the '(SELECT ROWNUM ...' query.
Then when you have both of those working wrap it in the outermost query.
At that point you can make it a PL/SQL function or if you really want to confuse people you can perform it all with one big UNION query (to take care of the case where there are no rows).
Good luck!
null

Similar Messages

  • Does anyone know how to calculate the impedance using waveforms

    does anyone know how to calculate the impedance using waveforms?

    studentproject wrote:
    the waveforms represent the voltage and current values across a capacitive load. I am trying to find out if there is a way to do automatic calculations using the inputs from the waveforms
    Hopefully a single sinusoid tone.  Otherwise things get really interesting.  Also know that impedance is based on the frequency.  I'll have to dig into this again.  I have not had to calculate an impedance in well over 10 years.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • How to get Listener Information using PL/SQL code

    How to get Listener Information using PL/SQL code

    user2075318 wrote:
    How to get Listener Information using PL/SQL codeThis approach (somewhat of a hack) can be used - but it does not really provide meaningful data at application layer.
    SQL> create or replace function TnsPing( ipAddress varchar2, port number default 1521 ) return varchar2 is
      2          type THexArray is table of varchar2(2);
      3          --// tnsping packet (should be 10g and 11g listener compatible)
      4          TNS_PING_PACKET constant THexArray := new THexArray(
      5                  '00', '57', '00', '00', '01', '00', '00', '00',
      6                  '01', '39', '01', '2C', '00', '00', '08', '00',
      7                  '7F', 'FF', '7F', '08', '00', '00', '01', '00',
      8                  '00', '1D', '00', '3A', '00', '00', '00', '00',
      9                  '00', '00', '00', '00', '00', '00', '00', '00',
    10                  '00', '00', '00', '00', '00', '00', '00', '00',
    11                  '00', '00', '00', '00', '00', '00', '00', '00',
    12                  '00', '00', '28', '43', '4F', '4E', '4E', '45',
    13                  '43', '54', '5F', '44', '41', '54', '41', '3D',
    14                  '28', '43', '4F', '4D', '4D', '41', '4E', '44',
    15                  '3D', '70', '69', '6E', '67', '29', '29'
    16          );
    17 
    18          socket  UTL_TCP.connection;
    19          txBytes number;
    20          rxBytes number;
    21          rawBuf  raw(1024);
    22          resp    varchar2(1024);
    23  begin
    24          socket := UTL_TCP.open_connection(
    25                          remote_host => ipAddress,
    26                          remote_port => port,
    27                          tx_timeout => 10
    28                  );
    29 
    30          --// convert hex array into a raw buffer
    31          for i in 1..TNS_PING_PACKET.Count loop
    32                  rawBuf := rawBuf || HexToRaw( TNS_PING_PACKET(i) );
    33          end loop;
    34 
    35          --// send packet
    36          txBytes := UTL_TCP.write_raw( socket, rawBuf, TNS_PING_PACKET.Count  );
    37 
    38          --// read response
    39          rxBytes := UTL_TCP.read_raw( socket, rawBuf, 1024 );
    40 
    41          UTL_TCP.close_connection( socket );
    42 
    43          --// convert response to varchar2
    44          resp := UTL_RAW.Cast_To_Varchar2( rawBuf );
    45 
    46          --// strip the header from the response and return the text only
    47          return( substr(resp,13) );
    48  end;
    49  /
    Function created.
    SQL>
    SQL> select tnsping( '10.251.93.30' ) as TNSPING from dual;
    TNSPING
    (DESCRIPTION=(TMP=)(VSNNUM=169869568)(ERR=0)(ALIAS=LISTENER))
    SQL> select tnsping( '10.251.95.69' ) as TNSPING from dual;
    TNSPING
    (DESCRIPTION=(TMP=)(VSNNUM=0)(ERR=0)(ALIAS=LISTENER))
    SQL>

  • How to create a counter using Oracle SQL Developer?

    Is there any way to create a counter using Oracle SQL Developer to create the below scenario. Meaning it will recorded down the name of user and ID and time and the date they login.
    Library portal home statistics shows how many users (outside and within the campus) visit the library portal.
    Page Access statistics is recorded on an hourly basis. Users may select the statistics by
    yearly (statistics displayed by all months in the selected year)
    monthly (statistics displayed by all days in the selected month)
    daily (statistics displayed by all hours in the selected day)

    I'm giving here one basic post - hope this will solve your problem --
    SQL>
    SQL>
    SQL> create table audit_info
      2   (
      3     usr        varchar2(50),
      4     log_time   timestamp(6)
      5    );
    Table created.
    SQL>
    SQL>
    SQL>  create table err_log
      2     (
      3       log_cd      varchar2(20),
      4       log_desc    varchar2(500)
      5     );
    Table created.
    SQL>
    SQL>
    SQL>   create or replace procedure ins_err(errcd   in  varchar2,
      2                                        errnm   in  varchar2)
      3    is
      4      pragma autonomous_transaction;
      5    begin
      6      insert into err_log values(errcd,errnm);
      7      commit;
      8    end;
      9  /
    Procedure created.
    SQL>
    SQL>
    SQL>   create or replace procedure ins_aud(ud   in varchar2,
      2                                        unm  in varchar2)
      3    is
      4      pragma autonomous_transaction;
      5    begin
      6      insert into audit_info values(ud,unm);
      7      commit;
      8    exception
      9      when others then
    10        ins_err(sqlcode,sqlerrm);
    11    end;
    12  /
    Procedure created.
    SQL>
    SQL>
    SQL>
    SQL> create or replace trigger log_odsuser1
      2   after logon on odsuser1.schema
      3   begin
      4     ins_aud('ODSUSER1',sysdate);
      5   exception
      6     when others then
      7       ins_err(sqlcode,sqlerrm);
      8   end;
      9  /
    Trigger created.
    SQL>
    SQL*Plus: Release 9.2.0.1.0 - Production on Tue Jun 12 12:21:09 2007
    Copyright (c) 1982, 2002, Oracle Corporation.  All rights reserved.
    Connected to:
    Oracle9i Enterprise Edition Release 9.2.0.6.0 - 64bit Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.6.0 - Production
    SQL>
    SQL>
    SQL>
    SQL> set serveroutput on
    SQL>
    SQL>
    SQL> select * from audit_info;
    USR
    LOG_TIME
    ODSUSER1
    12-JUN-07 12.00.00.00000000 AMHope this will solve your purpose.
    Regards.
    Satyaki De.

  • HOW TO START MAKING DATABASE USING ORACLE SQL PLUS in 10g?

    how will i create database using sql plus?
    does the code of sql applicable to it..?
    do i have to use the "create db <database name>", use and " create table also,.."
    pls help me..
    thanks

    At dos prompt :
    C:\>set ORACLE_SID=<your SID>
    C:\>sqlplus / as sysdba
    you get connected as sys user. Don't use this connection to create your own objects, create users instead.... but it would be useful to read some documentation, for example Starting SQL*Plus and manuals mentioned there.

  • How to calculate commodity code  using Tabe MARC and field STAWN.

    Hi All,
    how to calculate commodity code
    This attribute is stored at the Material/Plant level.  For each material, this attribute must be evaluated at all applicable plants. 
    u2022     If ALL values are the same, output the value to the report
    u2022     If all values are NOT the same, output u201CNot Consistentu201D in the column for the material
    The table to be used is MARC
    and the SAP technical field name is STAWN

    Hi Debrup,
    try this ... i have put down code here ... test it and make changes as needed.
    data:
    t_marc type standard table of marc with header line,
    lv_matnr like marc-matnr,
    lv_same type c.
    select MATNR WERKS STAWN
    from MARC
    into corresponding fields of table t_marc.
    sort t_marc by matnr werks stawn.
    loop at t_marc.
    at new matnr.
    clear lv_same.
    lv_matnr = t_marc-matnr.
    endat.
    at new stwan.
    * material is same but STWAN changed so flag change
    if lv_matnr = t_marc-matnr.
    lv_same = 'F'. " False.
    endif.
    endat.
    at end of matnr.
    if lv_same is intial.
    write : t_marc-matnr,t_marc-stwan.
    else.
    write : t_marc-matnr, 'Not Consistent'.
    endif.
    endat.
    endloop.
    hope this helps.
    Franc

  • How to iterate xml elements using PL/SQL

    Hello,
    Let's say I have the following xml:
    <A>
    <B name="b1">
    </B>
    <B name="b2">
    </B>
    </A>
    I would like to iterate over the B and sub-B elements using PL/SQL?
    Any help will be appreciated.

    Hi,
    You can use 'PL/SQL DOM API for XMLType (DBMS_XMLDOM)'
    to work with XML. You can check the example present at
    http://otn.oracle.com/docs/products/oracle9i/doc_library/release2/appdev.920/a96620/xdb08pls.htm#1041419
    to check how it does.
    The API for the package DBMS_XMLDOM is given on the same page(http://otn.oracle.com/docs/products/oracle9i/doc_library/release2/appdev.920/a96620/xdb08pls.htm#1040676)
    You can use them for your requirement.
    Regards,
    Anupama

  • How to send e-mail using PL/SQL

    I need to send e-mail using PL/SQL. Is it possible?
    Thanks in advance,
    Agnaldo

    Yes. Use the UTL_SMTP package

  • HOW TO CALL ANOTHER PAGE USING PL/SQL PDK?

    Hi,
    I am using pl/sql pdk to create portlets. When I need to call
    another page I am using wwpob_page.show(p_pageid) but instead it
    displays File Download wizard.
    Anyone knows workaroud for this?
    Are there any other ways to call other pages with portlets from
    pl/sql portlets?
    Thank you,
    ya

    Hello Yuri
    If you want to call any component of an application from PL/SQL
    you have to take a look to the manage of the component and then
    to Call Interface (Show), There you can see the way to call the
    component, but if you want to call a Page the way I found to do
    it, even thought it is not the best, was put an url like
    this /pls/portal30/url/page/PAGE_NAME on the link.
    I hope this could help you, if you dont understand please let me
    know and I'll give you a hand
    Ana Maria

  • How to create a Folder using a SQL Query?

    Hi
    How can I create a Folder (eg. C:\MyNewFolder) using SQL Query?

    Hi,
    I added some code in order to get the result from the xp_cmdshell command
    This returns null if successfull, if an error occurs returns the error message. May be useful instead of getting an sql error
    Code Snippet
    declare @cmdpath nvarchar(60), @Location nvarchar(100), @message nvarchar(max)
    set @Location = N'C:\Temp\Temp5'
    set @cmdpath = 'MD '+ @Location
    Create table #result
    result nvarchar(255)
    insert into #result (result) exec master.dbo.xp_cmdshell @cmdpath
    select @message = ISNULL(@message + ' - ','') + result from #result where result is not null
    select @message
    drop table #result
    Eralper
    http://www.kodyaz.com

  • How to create a database using a SQL statement? Please help.

    Connection con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.25:1521:mydb","system","12345678");
    but mydb database does not exist.
    I want to make a connection to oracle server without database name.
    How can I do?

    Colleauge, what is the purpose of making a connection to a non-existent database.
    connections are made to the database to retrieve some data or put some data.
    for which the database should exists.
    so please create the mydb database first using Database Configuration Assistant (DBCA) which is much easier as it is GUI based rather than doing it with sql scripts.

  • How to calculate the in use percentage of cache ?

    Hi, All,
    I have two questions here:
    1. Can we calculate the proper cache size based on the average key/data pair size and the number of key/data pairs? Is there any formula or something? ( I doubt it :), so next is the second question )
    2. If we set a fixed cache size, and ensure that it has almost 100% hit rate for all the entries accesses. Does this mean that the cache is enough? And if yes, can we calculate how much percentage of the cache is actually in use?
    Thanks in advance.

    Hi,
    user647934 wrote:
    1. Can we calculate the proper cache size based on the average key/data pair size and the number of key/data pairs? Is there any formula or something? ( I doubt it :), so next is the second question ) You can estimate that, just that you should also consider: the page size and how many records will fit on a page.
    Depending on your type of access method, you can check here for formulas that are estimating the total database size (you can find them here: http://www.oracle.com/technology/documentation/berkeley-db/db/ref/am_misc/diskspace.html ), and just translate that to the cache size. Be aware that any cache size less than 500MB is automatically increased by 25% to account for buffer pool overhead.
    user647934 wrote:
    2. If we set a fixed cache size, and ensure that it has almost 100% hit rate for all the entries accesses. Does this mean that the cache is enough? And if yes, can we calculate how much percentage of the cache is actually in use?I think that you can find everything you need by calling "db_stat -m" or DB_ENV->memp_stat for detailed cache statistics.
    db_stat: http://www.oracle.com/technology/documentation/berkeley-db/db/utility/db_stat.html
    DB_ENV->memp_stat: http://www.oracle.com/technology/documentation/berkeley-db/db/api_c/memp_stat.html
    The fields returned by this are:
    size_t st_gbytes;
    * Gigabytes of cache (total cache size is st_gbytes + st_bytes).
    size_t st_bytes;
    * Bytes of cache (total cache size is st_gbytes + st_bytes).
    u_int32_t st_ncache;
    * Number of caches.
    u_int32_t st_max_ncache;
    * Maximum number of caches, as configured with the DB_ENV->set_cache_max method.
    roff_t st_regsize;
    * Individual cache size, in bytes.
    size_t st_mmapsize;
    * Maximum memory-mapped file size.
    int st_maxopenfd;
    * Maximum open file descriptors.
    int st_maxwrite;
    * Maximum sequential buffer writes.
    db_timeout_t st_maxwrite_sleep;
    * Microseconds to pause after writing maximum sequential buffers.
    u_int32_t st_map;
    * Requested pages mapped into the process' address space (there is no available information about whether or not this request caused disk I/O, although examining the application page fault rate may be helpful).
    u_int32_t st_cache_hit;
    * Requested pages found in the cache.
    u_int32_t st_cache_miss;
    * Requested pages not found in the cache.
    u_int32_t st_page_create;
    * Pages created in the cache.
    u_int32_t st_page_in;
    * Pages read into the cache.
    u_int32_t st_page_out;
    * Pages written from the cache to the backing file.
    u_int32_t st_ro_evict;
    * Clean pages forced from the cache.
    u_int32_t st_rw_evict;
    * Dirty pages forced from the cache.
    u_int32_t st_page_trickle;
    * Dirty pages written using the DB_ENV->memp_trickle method.
    u_int32_t st_pages;
    * Pages in the cache.
    u_int32_t st_page_clean;
    * Clean pages currently in the cache.
    u_int32_t st_page_dirty;
    * Dirty pages currently in the cache.
    u_int32_t st_hash_buckets;
    * Number of hash buckets in buffer hash table.
    u_int32_t st_hash_searches;
    * Total number of buffer hash table lookups.
    u_int32_t st_hash_longest;
    * Longest chain ever encountered in buffer hash table lookups.
    u_int32_t st_hash_examined;
    * Total number of hash elements traversed during hash table lookups.
    u_int32_t st_hash_nowait;
    * Number of times that a thread of control was able to obtain a hash bucket lock without waiting.
    u_int32_t st_hash_wait;
    * Number of times that a thread of control was forced to wait before obtaining a hash bucket lock.
    u_int32_t st_hash_max_nowait;
    * The number of times a thread of control was able to obtain the hash bucket lock without waiting on the bucket which had the maximum number of times that a thread of control needed to wait.
    u_int32_t st_hash_max_wait;
    * Maximum number of times any hash bucket lock was waited for by a thread of control.
    u_int32_t st_region_wait;
    * Number of times that a thread of control was forced to wait before obtaining a cache region mutex.
    u_int32_t st_region_nowait;
    * Number of times that a thread of control was able to obtain a cache region mutex without waiting.
    u_int32_t st_mvcc_frozen;
    * Number of buffers frozen.
    u_int32_t st_mvcc_thawed;
    * Number of buffers thawed.
    u_int32_t st_mvcc_freed;
    * Number of frozen buffers freed.
    u_int32_t st_alloc;
    * Number of page allocations.
    u_int32_t st_alloc_buckets;
    * Number of hash buckets checked during allocation.
    u_int32_t st_alloc_max_buckets;
    * Maximum number of hash buckets checked during an allocation.
    u_int32_t st_alloc_pages;
    * Number of pages checked during allocation.
    u_int32_t st_alloc_max_pages;
    * Maximum number of pages checked during an allocation.
    u_int32_t st_io_wait;
    * Number of operations blocked waiting for I/O to complete.
    Please let me know if this helps.
    Thanks,
    Bogdan

  • How to return a dataset using PL/SQL?

    Hi All,
    I am a beginner in PL/SQL for Oracle 9i.
    I am converting a stored procedure written in T-SQL for SQL 2000.
    It basically goes like this:
    CREATE PROCEDURE CS_CidGetData
    @City varchar(30)
    AS
    SET NOCOUNT ON
    BEGIN
    SELECT
    FROM
    UserAccounts
    WHERE
    City LIKE @City + '%'
    END
    When this procedure is executed it sucessfully returns all the Users that match the criteria.
    In PL/SQL tried:
    CREATE OR REPLACE PROCEDURE USERACCOUNTSSELECT
    v_City IN UserAccounts.City%TYPE
    AS
    BEGIN
    SELECT
    FROM
    UserAccounts
    WHERE
    City LIKE v_City +'%';
    END;
    I need the stored procedure return a dataset back to the calling application.
    I realize I must define a return variable and use an INTO clause.
    Can anybody please show me how to do it?
    Thanks,
    Amintas

    Hi everybody,
    Thank you very much for your support.
    I have finally figured out how to do it.
    Here is the code just in case someone has the same question.
    You can test it using the default built-in database.
    Cheers,
    Amintas
    create or replace package pkg_emp
    AS
    type rc_emp is ref cursor;
    end;
    create or replace
    procedure SP_GetEmpData(v_empno IN emp.empno%Type,
    v_ename IN emp.ename%Type,
    emp_cur OUT pkg_emp.rc_emp)
    is
    begin
    if v_empno is not null and v_ename is null then
    OPEN emp_cur for
    select empno,ename,sal
    from emp
    where empno=v_empno;
    elsif v_ename is not null and v_empno is null then
    OPEN emp_cur for
    select empno,ename,sal
    from emp
    where ename like v_ename ||'%';
    end if;
    end;
    /* Testing the stored procedure */
    /*#1 */
    var myresultset refcursor;
    execute SP_GetEmpData(7900,null,:myresultset);
    print myresultset;
    /*#2 */
    var myresultset refcursor;
    execute SP_GetEmpData(null,'A',:myresultset);
    print myresultset;

  • Please!  How the hell do I use javax.sql in WSAD?

    I am migrating from VAJ 3.5 to WSAD 4.0. I am getting errors at certain import statements, such as the ones for javax.sql. I noticed that this package is not in WSAD. Is there another package it uses instead? How can I import this package?

    I highly doubt it uses another package. I know the javax.sql package comes with j2se 1.4 but I'm not sure about previous releases. If WSAD is like VAJ you may just need to add the package into the workspace.

  • How to calculate the subtotals using reuse_alv_grid_display_lvc

    Hi folks,
    How to get the subtotals of shipped quantity monthly wise using reuse_alv_grid_display_lvc.
    Thanks in Advance
    Rao

    Hi,
    As per the standard SAP, it is not possible to display the subtotal in a different field. The solution is remove the subtotal field from the internal table.
    In the slis_t_sortinfo_alv table pass the kunnr field with subtot = 'X'.
    I hope this will solve your query.
    Reward all useful answers.
    Thank you.

Maybe you are looking for

  • Addonics SATA Controller / KP Update

    A while back I posted regarding the Addonics ADSA3GPX1-2EM SATA controller card causing an immediate KP whenever I powered on the attached "SataVault" 2 drive enclosure. I also have an EP2 card from Sonnet that I was going to try. However while readi

  • Z 10 hotspot connection problems

    I am with Rogers and have a Z10 with OS version10.2.1.2141 Didn't know about the Tethering or Mobile Hotspot until a fiend told me and we both tried to start them up and for some reason both services presently say "Cannot start Mobile Hotspot due to

  • Why doesn't OS X backup work?

    After Instelling OS X 10.8.2. back up with Time Machine no longer works, it stops at 100.6 MB whereas >70 GB needs to be back up. Using a IOMEGA external HD the stop is at 2.26 GB of a >290 GB reported to be backed up? Anybody who has a solution to t

  • Installing on EBS R12 on Windows 7 Home Basic 64 Bit??

    Hi Experts, I ordered a Sony Vaio laptop with i5 processor, 500GB Hard Disk, 4 GB Ram just for installing EBS R12. It came with Windows 7 Home Basic 64 Bit..............Is there any article with step by step procedure?? What are your comments on Inst

  • MAC: Premiere Pro won't play. Nothing happens when pressing spacebar, nor play button on timeline

    Help!! Deadline looming! Nothing happens when I press play on any window or spacebar in Premiere Pro. The play button turns to stop and nothing else happens. I have also installed Premiere CS6 and everything works fine there.