SQL query question, how to improve it?

Hello everyone, I want to create a query with result in the following output. Each first-person Department starts with the letter A and goes to the top like this:

Name Department
A Person1 3
B Person2 3
C channels3 3
D Individu4 3
Person10 E 3

A 10 Person6
Person7 10 B
Person8 C 10

An Individu4 13
B Person9 13


It must be a SQL query, unfortunately no PL/SQL

I was able to create this query, but its lack. Department_id will be a variable, a person can choose a Department or several departments, so the request varies in size.

Select department_id, chr (64 + rownum)
from (select name, department_id
employees
where department_id = 3
order of id_but, naam
)
Union
Select department_id, chr (64 + rownum)
from (select name, department_id
employees
where department_id = 10
order of id_but, naam
)
Union
Select department_id, chr (64 + rownum)
from (select name, department_id
employees
where department_id = 13
order of id_but, naam
)
order of id_but, naam



The employees table has the following columns:
ID, name, department_id

Can someone help me with this query? Perhaps with the With clause?

Hello

You can use the analytic ROW_NUMBER function instead of ROWNUM. Like all analytical functions, ROW_NUMBER can do a calculation separated for each unique value in the PARTITION BY clause:

select        chr ( 64
           + ROW_NUMBER () OVER ( PARTITION BY  department_id
                         ORDER BY        id_but
                         ,             naam
                       )
           )     AS r_num
,        name
,       department_id
from       employees
where       department_id     IN (3, 10, 13)
order by  id_but
,       naam
;

If you do this in SQL * Plus, you can save for the departemnts user input (if it is a list separated by commas as ' 3, 10, 13', or a single value as "99") in a substitution variable (let's call it deptartment_id_list) and use the following WHERE clause:

where       department_id     IN (&department_id_list)

Tags: Database

Similar Questions

  • SQL query question

    I have a table named Test, data inserted as below

    col1 Val
    There3
    x1
    z2

    We write a query to output below:

    col1 Val
    x1
    There2
    z3

    Please suggest the best way to reach above result.

    It is not clear what you're trying to do, but you can use something like:

    Select col1,

    ROW_NUMBER() (any order of col1) val

    of the test

    /

    For example:

    with the trial as)

    Select 'x' col1, 3 val union double all the

    Select 'y', 2 double Union all

    Select 'z', 1 double

    )

    Select col1,

    ROW_NUMBER() (any order of col1) val

    of the test

    /

    C VAL
    - ----------
    x          1
    y          2
    z          3

    SQL >

    SY.

  • SQL Query Question campaign

    I have a table that has at least 40 values that I need to use as variables in CCA. My question is. If I write the query as follows:

    SELECT AS $Var1 of the value1, value2 AS $Var2, ETC... I do for 40 fields. Would it work if I just do a query where I

    SELECT * FROM DBNAME WHERE CALLER = "$ANI."

    and then simply use the column as variables names?

    If you need 40 variables in your campaign to act on and use in logic, then you must list and assign all 40 as your first example.

  • SQL Query Question of multiple criteria

    Hi all

    I currently have a query that provides me with a count for a criterion (C), but I also want to include the number of criteria (A) and (E) within the same query if possible. Here's what I have:

    SELECT B.MDA_LEV3_DEPT_NAME AS "TEU Area", AS COUNT (Z.MDA_EPAF_STATUS) PROJECT

    PS_MDA_EPAF_RQST Z, PS_MDA_EMPLOYEES B, PS_MDA_EPAF_WFXREF T

    WHERE MDA_EPAF_STATUS = 'C '.

    AND T.ORIGINATORID = Z.USERID

    AND Z.USERID = B.EMPLID

    AND Z.TRANSACTION_NBR = T.TRANSACTION_NBR

    B.MDA_LEV3_DEPT_NAME GROUP

    ORDER BY B.MDA_LEV3_DEPT_NAME;

    Which produces:

    Area of EVPProject Manager
    Office of VP University Affairs Sr5
    Cancer medicine30
    Cancer medicine - research49
    Cancer Prev & Pop science3
    Cancer Prev & science-Res Pop1
    Diagnostic Imaging2
    Information services16
    Internal medicine5
    Pathology/laboratory medicine2
    Pathology/laboratory medicine - Resch1
    Pediatrics13
    Provost and EVP departments1
    Radio-Oncology26
    Radio-Oncology - search2
    Regulatory Affairs1
    Surgery4
    Vice Provost research clinical1
    Vice Provost Science42

    But I want to understand (A) approved County and (E) which is pending County so it would look like:

    Area of EVPProject ManagerCounty approvedCounty pending
    Office of VP University Affairs Sr5
    Cancer medicine30
    Cancer medicine - research49
    Cancer Prev & Pop science3
    Cancer Prev & science-Res Pop1
    Diagnostic Imaging2
    Information services16
    Internal medicine5
    Pathology/laboratory medicine2
    Pathology/laboratory medicine - Resch1
    Pediatrics13
    Provost and EVP departments1
    Radio-Oncology26
    Radio-Oncology - search2
    Regulatory Affairs1
    Surgery4
    Vice Provost research clinical1
    Vice Provost Science42

    Maybe (guessing)

    SELECT B.MDA_LEV3_DEPT_NAME AS 'TEU Area. "

    PROJECT COUNT(CASE Z.MDA_EPAF_STATUS WHEN 'C' THEN 1 END) AS,

    COUNT(CASE Z.MDA_EPAF_STATUS WHEN 'A' THEN 1 END) APPROVED,

    AS COUNT(CASE Z.MDA_EPAF_STATUS WHEN 'P' THEN 1 END) PENDING

    OF PS_MDA_EPAF_RQST Z.

    B PS_MDA_EMPLOYEES,

    PS_MDA_EPAF_WFXREF T

    WHERE MDA_EPAF_STATUS ('C', 'A', 'P')

    AND T.ORIGINATORID = Z.USERID

    AND Z.USERID = B.EMPLID

    AND Z.TRANSACTION_NBR = T.TRANSACTION_NBR

    B.MDA_LEV3_DEPT_NAME GROUP

    ORDER BY B.MDA_LEV3_DEPT_NAME

    Concerning

    Etbin

  • SQL query on how to add a new column to display the result

    Select emp_code, < new column = 0 >
    from employee_table where < < condition > >

    syntax to add the new column?

    Published by: user9027633 on March 4, 2010 02:53

    user9027633 wrote:
    Select emp_code,
    from employee_table where >

    syntax to add the new column?

    Published by: user9027633 on March 4, 2010 02:53

    Want you like this

    selec emp_code, 0 new_column
      from employee_table
    
  • How to measure the performance of the sql query?

    Hi Experts,

    How to measure the cost of performance, efficiency and CPU of an sql query?

    What are all the measures available to a sql query?

    How to identify the optimal query writing?

    I use Oracle 9i...

    It'll be useful for me to write the effective query...

    Thanks and greetings

    PSRAM wrote:
    Could you tell me how to activate the PLUSTRACE role?

    First put on when you do a search on PLUSTRACE: http://forums.oracle.com/forums/search.jspa?threadID=&q=plustrace&objID=f75&dateRange=all&numResults=15&rankBy=10001

    Kind regards
    Rob.

  • How to get the value of a column in sql query?

    Hi, anyone knows how to get the value of a column in sql query?

    Here is my code, the value must be 1350079224397 in my PB, but I get 0

    QString query ("SELECT version FROM db_version");

    QVariant result = sda.execute (query);
    QVariantMap versionMap = result.toList () such () .toMap ();
    If (! versionMap.IsEmpty ())
    {
    qDebug()<"Version: "=""><>
    }

    OK, I have the solution

    QString query ("SELECT version as version FROM db_version");

  • How do I get recommendations sql query manually, its possible or not?

    I'm new dba oracle and my company gives me sql optimize, if research on google and knowledge, addm can give recommendations of sql query

    but I sql query and in addm can not give recommendations,

    I then how sql query performance increase... ?

    and the sql script to get the recommendations?

    Thanks in advance

    1. upgrade to oracle 11

    2. (take the topgun)

    Select / * + RESULT_CACHE * / a.empid, empname from

    (select empid, empname from india_emp

    where deptno <> 10 and empid NOT IN (105,202,11,45,695,646,726,8465,965,56,646,689,446)

    Union of all the

    Select empid, empname from us_emp

    where deptno <> 10 and empid NOT IN (105,202,11,45,695,646,726,8465,965,56,646,689,446)

    Union of all the

    Select empid, empname from uk_emp

    where deptno <> 10 and empid NOT IN (105,202,11,45,695,646,726,8465,965,56,646,689,446)

    Union of all the

    Select empid, empname from uae_emp

    where deptno <> 10 and empid NOT IN (105,202,11,45,695,646,726,8465,965,56,646,689,446)

    Union of all the

    Select empid, empname from brazl_emp

    where deptno <> 10 and empid NOT IN (105,202,11,45,695,646,726,8465,965,56,646,689,446)

    Union of all the

    Select empid, empname from chine_emp

    where deptno <> 10 and empid NOT IN (105,202,11,45,695,646,726,8465,965,56,646,689,446)

    Union of all the

    Select empid, empname from jpn_emp

    where deptno in (54,256,362,9879,24,46) and empid NOT IN (105,202,11,45,695,646,726,8465,965,56,646,689,446)

    ) a

    order by 2;

    3. run the query 3 times.

    The query will be lightning fast from the 3rd time

    4. read the full performance tuning guide

    http://docs.Oracle.com/CD/E11882_01/server.112/e41573/TOC.htm

  • How do I get the data of "Regulatory BOM" Formulation with SQL query output

    Hello

    We would like to implement a State of BiPublisher that displays "Regulation BOM" (wording-> click on TAB Formulation on exit Popup-> TAB Composition) information table.

    How could get us this information with an SQL query?

    Thank you

    Annarosa

    Hi, given 'Regulatory BOM' output of the Formulation are more complicated than expected. Attached is an example. You can test and make the appropriate changes to your report.

  • How to display time in 010403 format if the entry is transmitted as ' 1 hour, 4 minutes, 3 seconds"sql query

    How to display time in 010403 format if the entry is transmitted as ' 1 hour, 4 minutes, 3 seconds"sql query @.

    Hello

    You can try:

    Select lpad (regexp_substr ('1 hour, 4 minutes, 3 seconds ',' [[: digit:]] + ""), 2, '0')

    || LPAD (regexp_substr ('1 hour, 4 minutes, 3 seconds ',' [[: digit:]] +', 1, 2), 2, '0')

    || LPAD (regexp_substr ('1 hour, 4 minutes, 3 seconds ',' [[: digit:]] +' 1, 3), 2, '0')

    Double;

    but this requires maximum 99 hours/minutes/seconds ago in your entry.

  • How to select only the part by using the sql query

    Hello

    I have the task to retrieve only the integral of the input text by using the sql query.

    The entry is as follows

    Entry for the price setting

    $12.5 (FYI without space)

    $ 12.5 (FYI single space)

    $ 12.5 (double space FYI)

    $12.5 (FYI multiple space)

    $12.5 (FYI multiple space)

    Output expected of 12.5

    The price is the type varchar2 column in the store_price table.

    Please let me know how to achieve this.

    Thanks in advance.

    If this is always the case that you get a $ followed by a number of places, you can use something like:

    Select to_number (ltrim ('$ 12.5',' $')) DOUBLE

    or

    SELECT ltrim ('$ 12.5',' $') OF double

    but take care of your nls_numeric_character settings if they are defined so that, for example, a comma is the decimal separator, you will have a problem.

    HTH

  • How to identify columns that have the same data in a SQL query or function?

    Deal all,

    How to identify columns that have the same data in a SQL query or function? I have the sample data as below

    DEPT_IDEMP_IDCome on
    !CITYSTATECOUNTRY111 June 1983DELHIHUMAN RESOURCESIndia1218 January 1987DELHIHUMAN RESOURCESIndia1328 November 1985DELHIHUMAN RESOURCESIndia144 June 1985DELHIHUMAN RESOURCESIndia255 June 1983MUMBAIHDIndia266 June 1983MUMBAIHDIndia277 June 1983MUMBAIHDIndia288 Jun. 1983MUMBAIHDIndia399. June 1983GURGAONDLIndia31010 June 1983GURGAONDLIndia

    Now, I want to Indify columns that have the same data for the same Department ID.

    Is it possible in sql unique or do I have to write the function for this? Pls Help how to write?

    Thanks in advance.

    You can try this?

    WITH T1)

    DEPT_ID, EMP_ID, DATE OF BIRTH, CITY, STATE, COUNTRY

    ), ()

    SELECT 1, 1, TO_DATE('1.) June 1983', 'JJ. LUN. (YYYY'), 'DELHI', 'HR', 'INDIA' OF THE DUAL UNION ALL

    SELECT 1, 2, TO_DATE('18.) January 1987', 'JJ. LUN. (YYYY'), 'DELHI', 'HR', 'INDIA' OF THE DUAL UNION ALL

    SELECT 1, 3, TO_DATE('28.) November 1985', 'JJ. LUN. (YYYY'), 'DELHI', 'HR', 'INDIA' OF THE DUAL UNION ALL

    SELECT 1, 4, TO_DATE('4.) June 1985', 'JJ. LUN. (YYYY'), 'DELHI', 'HR', 'INDIA' OF THE DUAL UNION ALL

    SELECT 2.5, TO_DATE('5.) June 1983', 'JJ. LUN. (YYYY'), 'BOMBAY', 'HD', 'INDIA' OF THE DUAL UNION ALL

    SELECT 2.6, TO_DATE('6.) June 1983', 'JJ. LUN. (YYYY'), 'BOMBAY', 'HD', 'INDIA' OF THE DUAL UNION ALL

    SELECT 2.7, TO_DATE('7.) June 1983', 'JJ. LUN. (YYYY'), 'BOMBAY', 'HD', 'INDIA' OF THE DUAL UNION ALL

    SELECT 2.8, TO_DATE('8.) June 1983', 'JJ. LUN. (YYYY'), 'BOMBAY', 'HD', 'INDIA' OF THE DUAL UNION ALL

    SELECT 3, 9, TO_DATE('9.) June 1983', 'JJ. LUN. (YYYY'), 'GURGAON', 'DL', 'INDIA' OF THE DUAL UNION ALL

    SELECT 3.10, TO_DATE('10.) June 1983', 'JJ. LUN. (YYYY'), 'GURGAON', 'DL', 'INDIA' OF THE DOUBLE)

    SELECT DEPT_ID,

    RTRIM (XMLAGG (XMLELEMENT(A,VALS||',')). Extract ('//Text ()'), ',') COLUMNS_WITH_DUPLICATE

    DE)

    SELECT * FROM)

    SELECT DEPT_ID,

    EMP_ID,

    Date of birth

    CITY,

    STATE,

    COUNTRY

    DE)

    SELECT DEPT_ID,

    EMP_ID,

    Date of birth

    CITY,

    STATE,

    COUNTRIES,

    COUNT (*) OVER(PARTITION BY DEPT_ID ORDER BY EMP_ID DESC,DOB DESC,CITY DESC,STATE DESC, COUNTRY DESC) RN

    DE)

    SELECT DEPT_ID,

    CASE WHEN(CEID>1) AND THEN 'YES' ELSE 'NO' END AS EMP_ID.

    CASE WHEN(CDOB>1) THEN 'YES' ELSE 'NO' END AS DATE OF BIRTH,

    CASE WHEN(CCITY>1) AND THEN 'YES' ELSE 'NO' END AS CITY.

    CASE WHEN(CSTATE>1) AND THEN 'YES' ELSE 'NO' END AS STATE.

    CASE WHEN(CCOUNTRY>1) THEN 'YES' ELSE 'NO' END AS A COUNTRY

    DE)

    SELECT DISTINCT

    DEPT_ID,

    CEID,

    CDOB,

    CITY,

    CSTATE,

    CCOUNTRY

    DE)

    SELECT DEPT_ID,

    COUNT (*) TO THE CEID (DEPT_ID PARTITION, EMP_ID),.

    COUNT (*) ON CDOB (DEPT_ID SCORE, DATE OF BIRTH),

    COUNT (*) ON THE CITY (DEPT_ID PARTITION, CITY),

    COUNT (*) ON CSTATE (DEPT_ID PARTITION, STATE).

    COUNT (*) ON CCOUNTRY (DEPT_ID, COUNTRY PARTITION)

    FROM T1)))

    WHERE RN = 1)

    UNPIVOT (CLO FOR (VALS) IN (EMP_ID, DATE OF BIRTH, CITY, STATE, COUNTRY)))

    WHERE COLS = "YES".

    DEPT_ID GROUP;

    OUTPUT:

    DEPT_ID COLUMNS_WITH_DUPLICATE
    --------- ------------------------

    1 CITY, COUNTRY, STATE
    2 CITY, COUNTRY, STATE
    3 CITY, COUNTRY, STATE

    Post edited by: Parth272025

  • How to get an accurate sql query in oracle?

    Hi all

    Hope it's right,

    Mr President, I was using a SQL query that can be found here:

    Declare @nshiftmax datetime

    Set @nshiftmax = convert (time, DATEADD(N,1439,0))
    impression @nshiftmax

    When extracting the result is 23:59 01/01/1900

    and a single request more is there

    Declare @nshiftmax datetime

    Set @nshiftmax = convert (time, DATEADD (N, 0, 0))
    impression @nshiftmax

    When extracting the result is 01/01/1900 12:00 a.m..

    How the same oracle query result.

    Thanks in advance.

    Like this...

    SQL> select to_char(date '1900-01-01' + 1439/(24*60),'DD/MM/YYYY HH:MI AM') from dual;
    
    TO_CHAR(DATE'1900-0
    -------------------
    01/01/1900 11:59 PM
    
    SQL> select to_char(date '1900-01-01' + 0/(24*60),'DD/MM/YYYY HH:MI AM') from dual;
    
    TO_CHAR(DATE'1900-0
    -------------------
    01/01/1900 12:00 AM
    
  • How to achieve this using the sql query?

    Hello gurus,

    I have a table like this
    id    name
    1       a
    2       b
    3       c
    4       d
    5       e
    6       f
    7       g
    8       h
    9       i
    10     j
    11     k
    12     l
    13     m
    now my result should be like this
    id    name  id   name   id   name 
    1       a     6       f      11     k
    2       b     7       g     12     l
    3       c     8       h     13     m
    4       d     9       i
    5       e     10      j
    How to achieve by sql query?

    Thank you and best regards,
    friend

    Edited by: most wanted! February 22, 2012 05:55

    Hello

    Did you mean this:

    with a as
    (select 1 id ,'a' name from dual
    union all select 2 id ,'b' name from dual
    union all select 3 id ,'c' name from dual
    union all select 4 id ,'d' name from dual
    union all select 5 id ,'e' name from dual
    union all select 6 id ,'f' name from dual
    union all select 7 id ,'g' name from dual
    union all select 8 id ,'h' name from dual
    union all select 9 id ,'i' name from dual
    union all select 10 id ,'j' name from dual
    union all select 11 id ,'k' name from dual
    union all select 12 id ,'l' name from dual
    union all select 13 id ,'m' name from dual
    )
    
    select
      id_1
      ,name_1
      ,id_2
      ,name_2
      ,id_3
      ,name_3
    
    from
      (
      select
        id id_1
        ,name name_1
        ,lead(id,5) over (order by id) id_2
        ,lead(name,5) over (order by id) name_2
        ,lead(id,10) over (order by id)  id_3
        ,lead(name,10) over (order by id) name_3
        ,rownum r
      from
        a
      )
    where
      r <=5
    
    D_1                   NAME_1 ID_2                   NAME_2 ID_3                   NAME_3
    ---------------------- ------ ---------------------- ------ ---------------------- ------
    1                      a      6                      f      11                     k
    2                      b      7                      g      12                     l
    3                      c      8                      h      13                     m
    4                      d      9                      i
    5                      e      10                     j 
    

    Kind regards

    Peter

  • SQL query and question CFOUTPUT

    Hello

    I am trying to compare two tables in a database.  I need a few fields in a table of output, to compare a field between the two tables.  Users choose the tables.  I've written a SQL query that does what I need:

    < cfquery name = "getitems" datasource = "snapshot" >
    Select #endtable # .field9 #endtable # .field12, #endtable # .field4, #endtable # .field13, #endtable # .field2, #endtable # .field3, #starttable # .field3
    of #endtable #, #starttable #.
    "where #endtable # .field5 =' #form.field5 #"
    and #starttable # .field2 = #endtable # .field2
    < / cfquery >

    Problem is on the output.  You can see that I am selecting field3 in two tables.  I want also to two output field3 values.

    < cfoutput query = "getitems" >

    #field3 #.

    < / cfoutput >

    This gives me the value that was chosen as #endtable # .field3.

    How can I exit the other - .field3 of # #starttable?

    As mentioned, the table names are variable being passed in the query...  Thank you!

    Peter

    How can I exit the other - .field3 of # #starttable?

    Use an alias to give different names fields IE table.column AS unnom. Otherwise, cfquery do not know what field do you mean when you say "field3".

    Select #endtable # .field9, #endtable # .field12,.

    Be careful when using this type of sql. According to the source of your variables, this can pose a risk of sql injection.

Maybe you are looking for