Write into a single query

Hi,
I'm fetching supplier, Item, qty information from different tables.
Q1: Supplier Name, Quantity are the columns in my select clause, for only one particular item (hard coded).
But I want a single query which fulfills my below 2 requirements:
1. concatenate top 3 suppliers who has ordered this item with qty in descending order.
2. Sum of the quantity of this particular item ordered by all the supplier (not only top 3 suppliers).
for this, i've been executing Q1 twice.
I want to fetch these two requirements in one query!! Any help on this is appreciated.
Thanks,
Santhosh K

Hi, Santhosh,
Sreekanth Munagala wrote:
Hi,
Is this what you are looking for
DDL statements
create table  xx_item_master as
SELECT 10 Supp_id,'IT1' item, 50 quantity FROM DUAL UNION ALL
SELECT 20 Supp_id,'IT1' item, 100 quantity FROM DUAL UNION ALL
SELECT 30 Supp_id,'IT1' item, 150 quantity FROM DUAL UNION ALL
SELECT 40 Supp_id,'IT1' item, 25 quantity FROM DUAL UNION ALL
SELECT 10 Supp_id,'IT2' item, 150 quantity FROM DUAL UNION ALL
SELECT 20 Supp_id,'IT2' item, 100 quantity FROM DUAL UNION ALL
SELECT 30 Supp_id,'IT2' item, 50 quantity FROM DUALQuery
...That's perfect; thanks.
The query below gets the results you want for any one given item, as ypu requested:
WITH   group_by_supplier      AS
     SELECT       supp_id
     ,       ROW_NUMBER () OVER (ORDER BY SUM (quantity) DESC)     AS r_num
     ,       SUM (SUM (quantity)) OVER ()                              AS total_quantity
     FROM       xx_item_master
     WHERE       item     = :target_item
     GROUP BY  supp_id
SELECT     LTRIM ( SYS_CONNECT_BY_PATH (supp_id, ',')
           )               AS supp_list
,     total_quantity
FROM     group_by_supplier
WHERE     CONNECT_BY_ISLEAF     = 1
START WITH     r_num     = 1
CONNECT BY     r_num     = PRIOR r_num + 1
     AND     LEVEL     <= 3;You can easily adapt it to get several (or all) items at once, if you ever need that.

Similar Messages

  • Combine 2 Queries (from SAME table) into a SINGLE query

    I have this two queries (from SAME table), and want to combine into one SINGLE query, how?
    How can we use CASE WHEN THEN for such situation? 
    Query1:
    SELECT t_inner.*,
    Floor(t_inner.ProductiveTime/ 3600) || 'hr:' || LPAD(Floor(Mod(t_inner.ProductiveTime,3600) / 60),2,0) || 'min:' AS Productive_Time,
    Floor(t_inner.OperatorDownTime/ 3600) || 'hr:' || LPAD(Floor(Mod(t_inner.OperatorDownTime,3600) / 60),2,0) || 'min:' AS OperatorDown_Time
    FROM
    (SELECT SYSTEMTYPE,
    sum(TIME_TEST + TIME_STEP) AS ProductiveTime,
    sum(TIME_IDLE) AS OperatorDownTime
    FROM PFODS.PPL_TESTSYSTEMS_UTILISATION
    WHERE (SYSTEMTYPE = '0005-072')
    AND (TS_START >= to_date('13/01/2014', 'DD/MM/YYYY'))
    AND TS_End <= to_date('17/01/2014', 'DD/MM/YYYY') + 1 + (1/1440) +(59/86400)
    AND MONO != '9999999999'
    GROUP BY SYSTEMTYPE ) t_inner
    Query 2:
    SELECT t_inner.*,
    Floor(t_inner.MachineDownTime/ 3600) || 'hr ' || LPAD(Floor(Mod(t_inner.MachineDownTime,3600) / 60),2,0) || 'min' AS MachineDown_Time
    FROM
    (SELECT SYSTEMTYPE,
    sum(TIME_IDLE) AS MachineDownTime
    FROM PFODS.PPL_TESTSYSTEMS_UTILISATION
    WHERE (SYSTEMTYPE = '0005-072')
    AND (TS_START >= to_date('13/01/2014', 'DD/MM/YYYY'))
    AND TS_End <= to_date('17/01/2014', 'DD/MM/YYYY') + 1 + (1/1440) +(59/86400)
    AND MONO = '9999999999'
    GROUP BY SYSTEMTYPE) t_inner
    see http://postimg.org/image/koq87iyyz/  and
    http://postimg.org/image/fv3zxa38n

    with the first query, 
    SELECT t_inner.*,
    Floor(t_inner.ProductiveTime/ 3600) || 'hr:' || LPAD(Floor(Mod(t_inner.ProductiveTime,3600) / 60),2,0) || 'min' AS Productive_Time
    FROM
    (SELECT SYSTEMTYPE,
    --sum(TIME_TEST) AS TIME_TEST,
    --sum(TIME_SYSTEM) AS TIME_SYSTEM,
    --sum(TIME_STEP) AS TIME_STEP,
    --sum(TIME_IDLE) AS TIME_IDLE,
    sum(TIME_TEST + TIME_STEP) AS ProductiveTime
    FROM PFODS.PPL_TESTSYSTEMS_UTILISATION
    WHERE (SYSTEMTYPE = '0005-072')
    AND (TS_START >= to_date('13/01/2014', 'DD/MM/YYYY'))
    AND TS_End <= to_date('17/01/2014', 'DD/MM/YYYY') + 1 + (1/1440) +(59/86400)
    AND MONO != '9999999999'
    GROUP BY SYSTEMTYPE) t_inner
    it gives output as from 
    http://postimg.org/image/koq87iyyz/
    with the second query,
    SELECT t_inner.*,
    Floor(t_inner.MachineDownTime/ 3600) || 'hr ' || LPAD(Floor(Mod(t_inner.MachineDownTime,3600) / 60),2,0) || 'min' AS MachineDown_Time
    FROM
    (SELECT SYSTEMTYPE,
    sum(TIME_IDLE) AS MachineDownTime
    FROM PFODS.PPL_TESTSYSTEMS_UTILISATION
    WHERE (SYSTEMTYPE = '0005-072')
    AND (TS_START >= to_date('13/01/2014', 'DD/MM/YYYY'))
    AND TS_End <= to_date('17/01/2014', 'DD/MM/YYYY') + 1 + (1/1440) +(59/86400)
    AND MONO = '9999999999'
    GROUP BY SYSTEMTYPE) t_inner
    it gives output as from 
    http://postimg.org/image/fv3zxa38n/
    I want to come those 2 queries into a single query, such that it gives both outputs as above. Let me know if you need any other information. thanks.

  • I have these below queries. How do I join these 3 queries into a single query?

    1st query:
    SELECT TOP(1) @tmpOnlineCat = ac.AlertCatID
    FROM alert.AlertCategory ac
    WHERE ac.FkAlertID = 2
    AND ac.FkAlertTypeID = 3
    2nd query
    SELECT TOP(1) @tmpOfflineCat = ac.AlertCatID
    FROM alert.AlertCategory ac
    WHERE ac.FkAlertID = 3
    AND ac.FkAlertTypeID = 3
    3rd query
    INSERT INTO item.ItemOnlineOfflineAlertCategory
    VALUES
    @tmpPkItemID,
    @tmpOfflineCat,
    @tmpOnlineCat
    mayooran99

    I think this is all what you need!
    INSERT INTO item.ItemOnlineOfflineAlertCategory
    SELECT @tmpPkItemID,
    MAX(CASE WHEN FkAlertID = 2 THEN AlertCatID END) AS tmpOnlineCat,
    MAX(CASE WHEN FkAlertID = 3 THEN AlertCatID END) AS tmpOfflineCat
    FROM alert.AlertCategory
    WHERE FkAlertTypeID = 3
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Can we combine Query for cancelled requisitions and query for internal requisitions without internal sales order into a single query

    Hi All,
    Greetings.
    I have two queries namely,
    1.Query for cancelled requisitions and
    2.Query for Internal Requisitions without Internal Sales Orders.
    I was on a task to combine those two queries..
    Can we do that? if so, please help me do that..
    Thanks in Advance,
    Bhaskar.

    Hi All,
    Greetings.
    I have two queries namely,
    1.Query for cancelled requisitions and
    2.Query for Internal Requisitions without Internal Sales Orders.
    I was on a task to combine those two queries..
    Can we do that? if so, please help me do that..
    Thanks in Advance,
    Bhaskar.

  • Possible to combine two xml documents into a single query?

    In ASP, PHP, etc. if I wanted to combine two tables and
    filter by one =
    item, I would create a recordset combining the two on one
    common element =
    and have one recordset. Is that possible with xml documents
    and Spry =
    datasets?
    I have xml information sent to me 4 times a day from a
    weather service. =
    This happens automatically, but the two xml documents
    (current.xml and =
    forecast.xml) are set in stone by the service. However, if in
    my Spry =
    dataset, I could combine them so I could list the 15 cities
    in a master =
    region and have tabs for the current conditions and forecast
    which would =
    each access a separate xml document but needs to do that from
    the city =
    link on the left, that would work great.
    Can I do this as I would be able to if I had a database with
    different =
    tables?
    Thanks!
    Nancy

    Hi Kin:
    They are really static xml files that are placed in a folder
    directly by =
    the weather service. The files in question are current.xml
    and =
    forecast.xml.
    And there is not one per city .. but just one of each. the
    location =
    node in current.xml and the citycode node in forecast.xml
    contain the =
    same information.
    If I were doing this in a recordset with a database, I would
    write =
    something like SELECT whatever from current, forecast WHERE =
    current.location =3D forecast.citycode AND current.location
    =3D variable =
    (which would be what is clicked on).
    This sets up a master/detail arrangement for the first one
    that works =
    fine. Click on the city code (which I have to write something
    to say If =
    location =3D FAT, document.write "Fresno" and so on) and the
    rest of the =
    current information displays fine on the right side of the
    page. Now I =
    have to marry that to the forecast.xml file so that when
    citycode =3D =
    FAT, the five day information for Fresno shows up .. and so
    on. I was =
    planning to use Spry tabs or whatever to show the data.
    <!--
    var dsCurrent =3D new Spry.Data.XMLDataSet("current.xml", =
    "weather/current");
    //-->
    </script>
    </head>
    <body>=20
    <div class=3D"MasterDetail">
    <div spry:region=3D"dsCurrent"
    class=3D"MasterContainer">
    <div class=3D"MasterColumn" spry:repeat=3D"dsCurrent" =
    spry:setrow=3D"dsCurrent" spry:hover=3D"MasterColumnHover" =
    spry:select=3D"MasterColumnSelected">{location}</div>
    </div>
    <div spry:detailregion=3D"dsCurrent"
    class=3D"DetailContainer">
    <div class=3D"DetailColumn">{phrase}</div>
    <div class=3D"DetailColumn">{temp}</div>
    <div class=3D"DetailColumn">{temp/@units}</div>
    <div class=3D"DetailColumn">{aptemp}</div>
    <div class=3D"DetailColumn">{aptemp/@unit}</div>
    <div class=3D"DetailColumn">{wndchl}</div>
    <div class=3D"DetailColumn">{wndchl/@unit}</div>
    <div class=3D"DetailColumn">{rhumid}</div>
    <div class=3D"DetailColumn">{rhumid/@unit}</div>
    <div class=3D"DetailColumn">{wind_dir}</div>
    <div class=3D"DetailColumn">{windspeed}</div>
    <div
    class=3D"DetailColumn">{windspeed/@unit}</div>
    <div class=3D"DetailColumn">{pres}</div>
    <div class=3D"DetailColumn">{pres/@unit}</div>
    <div class=3D"DetailColumn">{vis}</div>
    <div class=3D"DetailColumn">{vis/@unit}</div>
    <div class=3D"DetailColumn">{icon}</div>
    </div>
    Arnout gave me some suggestions .. but so far, I haven't
    gotten either =
    of them to work. Also I am trying to get some ideas from spry
    Samples =
    from the Spry home page/samples area, but again .. not yet.
    Thanks,
    Nancy
    "kinblas" <[email protected]> wrote in
    message =
    news:[email protected]...
    >I don't think you need to combine them just so they can
    render in a =
    tabbed=20
    > widget. We're still missing a couple of key pieces of
    information. =
    What does=20
    > the data that is used in the master region look like?
    Are what you =
    refer to as=20
    > current.xml and forecast.xml really static files? Or are
    they =
    dynamically=20
    > generated by a server side script (php/cf/etc)? There is
    one current =
    and=20
    > forecast xml per city right?
    >=20
    > I ask these questions because you may be able to simply
    set up a =
    master detail=20
    > relationship between 3 data sets and just use those
    within a region(s) =
    that=20
    > build up the tab widget. Assuming you were getting the
    list of cities =
    from a=20
    > 3rd source, you could set up something like this:
    >=20
    >=20
    > var dsCities =3D new Spry.Data.XMLDataSet("cities.xml",
    =
    "/cities/city");
    > var dsCurrent =3D new=20
    >
    Spry.Data.XMLDataSet("current.php?location=3D{dsCities::name}",=20
    > "/weather/current");
    > var dsForecast =3D new=20
    >
    Spry.Data.XMLDataSet("forecast.php?citycode=3D{dsCities::name}",=20
    > "/weather/forecast/day");
    >=20
    >=20
    > ...
    >=20
    >=20
    > <div id=3D"TabbedPanels1" class=3D"TabbedPanels">
    > <ul class=3D"TabbedPanelsTabGroup">
    >
    Current</li>
    >
    Forecast</li>
    >
    > <div class=3D"TabbedPanelsContentGroup">
    > <div class=3D"TabbedPanelsContent"
    spry:region=3D"dsCurrent">
    > {temp}{temp/@unit}
    > </div>
    > <div class=3D"TabbedPanelsContent"
    spry:region=3D"dsForecast">
    >
    > <li spry:repeat=3D"dsForecast">{name}<br
    />High: =
    {high}{high/@unit}<br=20
    > />Low: {low}{low/@unit}</li>
    >
    > </div>
    > </div>
    > </div>
    >=20
    >=20
    >=20
    > --=3D=3D Kin =3D=3D--
    >

  • How to combine below 4 queries into a single query?

    SELECT COUNT(*) AS NORMAL_PASS
    FROM (
    SELECT MAINSERNO
    FROM SGSTUDENT.PPL_PRODUCT_TESTID2
    WHERE (MONO = '5954556' AND TESTMODE =1 AND TESTFLAG =1)
    SELECT COUNT(*) AS NORMAL_FAIL
    FROM (
    SELECT MAINSERNO
    FROM SGSTUDENT.PPL_PRODUCT_TESTID2
    WHERE (MONO = '5954556' AND TESTMODE =1 AND TESTFLAG =2)
    SELECT COUNT(*) AS REPEAT_PASS
    FROM (
    SELECT MAINSERNO
    FROM SGSTUDENT.PPL_PRODUCT_TESTID2
    WHERE (MONO = '5954556' AND TESTMODE =2 AND TESTFLAG =1)
    SELECT COUNT(*) AS REPEAT_FAIL
    FROM (
    SELECT MAINSERNO
    FROM SGSTUDENT.PPL_PRODUCT_TESTID2
    WHERE (MONO = '5954556' AND TESTMODE =2 AND TESTFLAG =2)

    Are you looking for the below:
    SELECT COUNT(*) as Cnt, 'NORMAL_PASS' as [Type]
    FROM (
    SELECT MAINSERNO
    FROM SGSTUDENT.PPL_PRODUCT_TESTID2
    WHERE (MONO = '5954556' AND TESTMODE =1 AND TESTFLAG =1)
    Union All
    SELECT COUNT(*) , 'NORMAL_FAIL'
    FROM (
    SELECT MAINSERNO
    FROM SGSTUDENT.PPL_PRODUCT_TESTID2
    WHERE (MONO = '5954556' AND TESTMODE =1 AND TESTFLAG =2)
    Union All
    SELECT COUNT(*) , 'REPEAT_PASS'
    FROM (
    SELECT MAINSERNO
    FROM SGSTUDENT.PPL_PRODUCT_TESTID2
    WHERE (MONO = '5954556' AND TESTMODE =2 AND TESTFLAG =1)
    Union All
    SELECT COUNT(*) , 'REPEAT_FAIL'
    FROM (
    SELECT MAINSERNO
    FROM SGSTUDENT.PPL_PRODUCT_TESTID2
    WHERE (MONO = '5954556' AND TESTMODE =2 AND TESTFLAG =2)
    Or
    SELECT MAINSERNO,Count(Case when TESTMODE =1 AND TESTFLAG =1 Then 1 Else NULL End) as 'Normal_Pass',
    Count(Case when TESTMODE =1 AND TESTFLAG =2 Then 1 Else NULL End) as 'Normal_Fail',
    Count(Case when TESTMODE =2 AND TESTFLAG =1 Then 1 Else NULL End) as 'Repeat_Pass',
    Count(Case when TESTMODE =2 AND TESTFLAG =2 Then 1 Else NULL End) as 'Repeat_Pass'
    FROM SGSTUDENT.PPL_PRODUCT_TESTID2
    WHERE (MONO = '5954556')

  • Max in a single query

    how i can write in a single query from 2 following for get max value?
              SELECT NVL(MAX(number1),0)+1 INTO      max1 FROM table1
                   WHERE TO_NUMBER(tO_CHAR(DATA1,'YYYY')) = ANNOX;
              SELECT NVL(MAX(N_number1),0)+1 iNTO      max2     FROM table2
                   WHERE TO_NUMBER(tO_CHAR(DATA2,'YYYY')) = ANNOX
                   AND tipo = 'xx';
    for example:
         IF      max1 > max2 then
                        myvar := max1
         ELSE
                        myvar := max2
         END IF;
    thanks for help

    Try this.
    SELECT greatest(NVL(MAX(a.number1),0)+1,  NVL(MAX(b.N_number1),0)+1) value
    INTO max1
    FROM table1 a
        ,table2 b
    WHERE TO_NUMBER(tO_CHAR(a.DATA1,'YYYY')) = TO_NUMBER(tO_CHAR(b.DATA2,'YYYY'))
    and TO_NUMBER(tO_CHAR(a.DATA1,'YYYY')) = ANNOX
    AND b.tipo = 'xx';
    not tested
    Cheers
    Sarma.

  • Populate Multiple Items bundled in a single query

    Hello,
    I am trying to create a report in which I have mulitple items that I want to populate. All of these use the same query but use different rows in the query to populate themselves. My question is:-
    Is there a way to bundle the item assignment into a single query and populate the items from there? I want to reduce the time it takes for me to display the report and just hit the database once instead.

    Hi there,
    when u say report, i think its a more of a page showing few items on a region whose values are populated from Database rather than a SQL report which will not have any items. Is that correct?
    yes, multiple items of a page can be assigned values at once.
    assume: P1_ITEM1,P1_ITEM2,P1_ITEM3,P1_ITEM4 are different items on a page, an "On-Load Before Header" PL/SQL process can be created to assign values to the items in this way:
    SELECT tab.col1,tab.col2,tab.col3,tab.col4 INTO :P1_ITEM1,:P1_ITEM2,:P1_ITEM3,:P1_ITEM4 FROM TABLE tab;
    Item "Source Used" should be of type: Only When Current Value in session state is null
    Source Type: PL/SQL Expression or function
    and Source Value or EXpression should be some thing like this :P1_ITEM1
    Hope this helps.
    Edited by: Chaitu_Apex on Mar 10, 2010 2:43 PM

  • Double aggregation in a single query block doesn't make any sence.

    How can I argue with something that apparently has been cast in stone by ANSI SQL committee? Well the answer is famous: "Search any park in any city: you'll find no statue of committee".
    OK, why
    select count(1) from (
    select deptno from emp
    group by deptno
    is an easy to understand query, and why
    select count(count(*)) from emp
    group by deptno
    is not? I already mentioned one reason why count shouldn't accept any arguments, therefore count(count(*)) is a nonsence.
    The other reason is that aggregation without grouping is essentially aggregation within a single group. Once you realize that
    select sum(1) from emp
    is the same as
    select sum(1) from emp
    group by -1
    (where -1 or any other constant for that matter is a dummy pseudocolumn), then it becomes obvious that what we are doing in the infamous
    select count(count(*)) from emp
    group by deptno
    is a query with two blocks
    select count(1) from (
    select deptno from emp
    group by deptno
    ) group by -1
    We are not allowed to combine two "group by" into a single query, aren't we?

    Aggregate function always goes together with grouping. Grouping can partition the set of rows into many classes or a single class. Therefore, if we have 2 nested aggregation functions, we'd better be able to identify the corresponding groupings easily:
    select state, avg(min(tax_return)) from household
    group by city, state then statewhich is a shorthand for
    select state, avg(m) from (
       select city, state, min(tax_return) m
       from household
       group by city, state
    ) group by stateSpeaking of double aggregation, it is frequent in graph queries. The part explosion query is posted repeatedly virtually every month on this fine forum:-) The part explosion is double aggregation: multiply the quantities along each path in the assembly hierarchy. Then add the quantities along alternative paths. Likewise, finding a shortest path between two nodes in a graph is double aggregation query. First, we calculate the length buy adding the distances along each path, and then we choose a path with minimal length. Wouldn't it be nice to have this double aggregation wired into the connect by syntax? Note that connect_by_path is a surrogate aggregate which concatenates strings. People invent all kind of functions which parse this path and make other aggregates out of this value (such as sum and product).

  • Oracle query - Merging multiple rows into a single row output

    Hi All,
    I have to have a multiple row output to be converted into a single row output.My current output looks as follows:
    ID YR INC_CODE OFFN SCHOOLNO
    8006 2002 00175 SC03 12
    8006 2002 00175 DC06 12
    8006 2002 00175 DC03 12
    8006 2002 00175 DC02 12
    ID,INCIDENT CODE,OFFENSE are all Primary keys
    So I need the output as follows:(IN ONE ROW)
    ID YR INC_CODE OFFN1 OFFN2 OFFN3 OFFN4 SCHOOLNO
    8006 2002 00175 SC03 DC06 DC03 DC02 12
    Can you help me on this since have been spinning the wheel and this has to be a query since will have couple of tables join to produce a materialized view.
    Thanks in advance

    Hi Nigel,
    Thanks for the reply I tested out the portion having the decode and I get the output as follows:
    ID YR INC_CODE OFFN1 OFFN2 OFFN3 OFFN4 OFFN5
    8982 2002 2175 DOC01 -----------------------
    8982 2002 2175 DOC02-------------------
    8982 2002 2175 DOC03------------
    8982 2002 2175 DOC06-------
    8982 2002 2175 SCV03
    There is no value as max for OFFN and each INC_CODE MAY HAVE UP TO A MAX OF 5 OFFN.My query is as follows:
    select distinct STU_STUDENT_ID, INC_BEG_SCH_YR,INC_INCIDENT_CODE
    , decode(rank() over (partition by INC_CODE order by OFFN),1,OFFN,null) as offn1
    , decode(rank() over (partition by INC_CODE order by OFFN),2,OFFN,null) as offn2
    , decode(rank() over (partition by INC_CODE order by OFFN),3,OFFN,null) as offn3
    , decode(rank() over (partition by INC_CODE order by OFFN),4,OFFN,null) as offn4
    , decode(rank() over (partition by INC_CODE order by OFFN),5,OFFN,null) as offn5
    from stu_offn where
    stu_offn.ID = '8982' and stu_offn.INC_CODE = '2175'
    (****Where clause is just given to just check a value)
    So as you know I need to just have all the OFFN in a single row ie as follows:
    ID YR INC_CODE OFFN1 OFFN2 OFFN3 OFFN4 OFFN5
    8982 2002 2175 DOC01 DOC02 DOC03 DOC06 SCV03
    Can you just give me a step by step procedure to go through this and the table in this case is just 'STU_OFFN'
    Thanks for the earlier reply appreciate it!
    ****Sending this again to show the exact way the output is coming

  • Is there a way to combine their query results into a single function

    say I have a bunch of functions that return a query:
    <cffunction name="getDeals" access="remote"
    returntype="query">
    <cffunction name="getDeals2" access="remote"
    returntype="query">
    is there a way to combine their query results into a single
    function that returns a struct of the various results?

    Umm, it's probably more suited to an array - effectively
    making it into a list of queries. You'd then loop the array and
    output each.
    I use a similar approach when creating system messages to the
    user. Most of my functions that are called do their bit, then at
    the end call another function I call "messages". This function
    grabs whatever my function sends and appends it to a messages
    array.
    This way enables me to output a long list of messages -
    because I could be calling several functions at the same time. If I
    just output a message from each function, each one would overwrite
    the other. So I'd get one message at a time.
    Immediately after it's output, I then destroy the message
    array so that old messages aren't kept inside of it.
    Mikey.

  • Need help with query joining several tables into a single return line

    what i have:
    tableA:
    puid, task
    id0, task0
    id1, task1
    id2, task2
    tableB:
    puid, seq, state
    id0, 0, foo
    id0, 1, bar
    id0, 2, me
    id1, 0, foo
    id2, 0, foo
    id2, 1, bar
    tableC:
    puid, seq, date
    id0, 0, 12/21
    id0, 1, 12/22
    id0, 2, 12/22
    id1, 0, 12/23
    id2, 0, 12/22
    id2, 1, 12/23
    what i'd like to return:
    id0, task0, 12/21, 12/22, 12/22
    id1, task1, 12/23, N/A, N/A
    id2, task2, 12/22, 12/23, N/A
    N/A doesn't mean return the string "N/A"... it just means there was no value, so we don't need anything in this column (null?)
    i can get output like below through several joins, however i was hoping to condense each "id" into a single line...
    id0, task0, 12/21
    id0, task0, 12/22
    id0, task0, 12/23
    id1, task1, 12/23
    is this possible fairly easily?
    Edited by: user9979830 on Mar 29, 2011 10:53 AM
    Edited by: user9979830 on Mar 29, 2011 10:58 AM

    Hi,
    Welcome to the forum!
    user9979830 wrote:
    what i have:...Thanks for posting that so clearly!
    Whenever you have a question, it's even better if you post CREATE TABLE and INSERT statements for your sample data, like this:
    CREATE TABLE     tablea
    (       puid     VARCHAR2 (5)
    ,     task     VARCHAR2 (5)
    INSERT INTO tablea (puid, task) VALUES ('id0',  'task0');
    INSERT INTO tablea (puid, task) VALUES ('id1',  'task1');
    INSERT INTO tablea (puid, task) VALUES ('id2',  'task2');
    CREATE TABLE     tablec
    (       puid     VARCHAR2 (5)
    ,     seq     NUMBER (3)
    ,     dt     DATE          -- DATE is not a good column name
    INSERT INTO tablec (puid, seq, dt) VALUES ('id0',  0,  DATE '2010-12-21');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id0',  1,  DATE '2010-12-22');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id0',  2,  DATE '2010-12-22');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id1',  0,  DATE '2010-12-23');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id2',  0,  DATE '2010-12-22');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id2',  1,  DATE '2010-12-23');This way, people can re-create the problem and test their ideas.
    It doesn't look like tableb plays any role in this problem, so I didn't post it.
    Explain how you get the results from that data. For example, why do you want this row in the results:
    PUID  TASK  DT1        DT2        DT3
    id0   task0 12/21/2010 12/22/2010 12/22/2010rather than, say
    PUID  TASK  DT1        DT2        DT3
    id0   task0 12/22/2010 12/21/2010 12/22/2010? Does 12/21 have to go in the first column because it is the earliest date, or is it because 12/21 is related to the lowest seq value? Or do you even care about the order, just as long as all 3 dates are shown?
    Always say what version of Oracle you're uisng. The query below will work in Oracle 9 (and up), but starting in Oracle 11, the SELECT ... PIVOT feature could help you.
    i can get output like below through several joins, however i was hoping to condense each "id" into a single line... Condensing the output, so that there's only one line for each puid, sounds like a job for "GROUP BY puid":
    WITH     got_r_num     AS
         SELECT     puid
         ,     dt
         ,     ROW_NUMBER () OVER ( PARTITION BY  puid
                                   ORDER BY          seq          -- and/or dt
                           )         AS r_num
         FROM    tablec
    --     WHERE     ...     -- If you need any filtering, put it here
    SELECT       a.puid
    ,       a.task
    ,       MIN (CASE WHEN r.r_num = 1 THEN r.dt END)     AS dt1
    ,       MIN (CASE WHEN r.r_num = 2 THEN r.dt END)     AS dt2
    ,       MIN (CASE WHEN r.r_num = 3 THEN r.dt END)     AS dt3
    ,       MIN (CASE WHEN r.r_num = 4 THEN r.dt END)     AS dt4
    FROM       tablea    a
    JOIN       got_r_num r  ON   a.puid  = r.puid
    GROUP BY  a.puid
    ,            a.task
    ORDER BY  a.puid
    ;I'm guessing that you want the dates arranged by seq; that is, for each puid, the date related to the lowest seq comes first, regardless of whther that date is the earliest date for that puid or not. If that's not what you need, then change the analytic ORDER BY clause.
    This does not assume that the seq values are always consecutive integers (0, 1, 2, ...) for each puid. You can skip, or even duplicate values. However, if the values are always consecutive integers, starting from 0, then you could simplify this. You won't need a sub-query at all; just use seq instead of r_num in the main query.
    Here's the output I got from the query above:
    PUID  TASK  DT1        DT2        DT3        DT4
    id0   task0 12/21/2010 12/22/2010 12/22/2010
    id1   task1 12/23/2010
    id2   task2 12/22/2010 12/23/2010As posted, the query will display the first 4 dts for each puid.
    If there are fewer than 4 dts for a puid, the query will still work. It will leave some columns NULL at the end.
    If there are more than 4 dts for a puid, the query will still work. It will display the first 4, and ignore the others.
    There's nothing special about the number 4; you could make it 3, or 5, or 35, but whatever number you choose, you have to hard-code that many columns into the query, and always get that many columns of output.
    For various ways to deal with a variable number of pivoted coolumns, see the following thread:
    PL/SQL
    This question actually doesn't have anything to do with SQL*Plus; it's strictly a SQL question, and SQL questions are best posted on the "SQL and PL/SQL" forum:
    PL/SQL
    If you're not sure whether a question is more of a SQL question or a SQL*Plus question, then post it on the SQL forum. Many more people pay attention to that forum than to this one.

  • Insert into two tables with a single query (same ID)

    Hello,
    I want to insert two tables at the same time ( with a single query) provided that both records get inserted with the same id. How do I do this?
    Table Movies
    id
    name
    Table Category
    movie_id
    cat_typea) Insert into first table, retrieve the id (may be by using my_sequence.currval and then insert into another table.
    issue: Makes three query to the db, I am also guessing that when multiple people try to insert there will be an issue, I might be wrong.
    I don't have any other idea.
    Greatly appreciated!

    Why don't use multitable insert ? It's available from 9i.
    A sequence.nextval will return the same value within the whole instruction
    so all records can be inserted with the same id.
    Look at this example:
    DROP TABLE A;
    DROP TABLE B;
    drop sequence a_seq;
    CREATE TABLE A(
      ID NUMBER,
      FIRSTNAME VARCHAR2(50)
    CREATE TABLE B AS
    SELECT id, firstname lastname FROM a;
    CREATE SEQUENCE a_seq
    START WITH 1;
    INSERT ALL
    INTO A(ID, FIRSTNAME) VALUES(A_SEQ.NEXTVAL, FNAME)
    INTO B(ID, LASTNAME) VALUES(A_SEQ.NEXTVAL, LNAME)
    SELECT 'fname ' || LEVEL FNAME, 'lname ' || LEVEL LNAME
    FROM DUAL
    CONNECT BY LEVEL < 10
    COMMIT;
    SELECT * FROM A;
    SELECT * FROM b;
    DROP TABLE A succeeded.
    DROP TABLE B succeeded.
    drop sequence a_seq succeeded.
    CREATE TABLE succeeded.
    CREATE TABLE succeeded.
    CREATE SEQUENCE succeeded.
    18 rows inserted
    commited
    ID                     FIRSTNAME                                         
    3                      fname 1                                           
    4                      fname 2                                           
    5                      fname 3                                           
    6                      fname 4                                           
    7                      fname 5                                           
    8                      fname 6                                           
    9                      fname 7                                           
    10                     fname 8                                           
    11                     fname 9                                           
    9 rows selected
    ID                     LASTNAME                                          
    3                      lname 1                                           
    4                      lname 2                                           
    5                      lname 3                                           
    6                      lname 4                                           
    7                      lname 5                                           
    8                      lname 6                                           
    9                      lname 7                                           
    10                     lname 8                                           
    11                     lname 9                                           
    9 rows selected

  • Reorder with just a single Query?

    If I have a table like
    ID | Desc | Sortorder
    1 One 3
    4 Two 2
    6 Three 1
    Is there a way I can use a single query to change the Sortorder to 1,2,3 based on my ORDER BY ID without having to write a script?

    and a complete example
    SQL> create table   x as
      2  (
      3  select 1 id, 'One' descr,  3 sortorder from dual union all
      4  select 4 id, 'Two' descr,  2 sortorder from dual union all
      5  select 6 id, 'Three' descr,  1 sortorder from dual
      6  )
      7  /
    Table created.
    SQL> select *
      2    from x
      3  /
            ID DESCR  SORTORDER
             1 One            3
             4 Two            2
             6 Three          1
    SQL> merge into x
      2  using (
      3  select id
      4       , row_number() over (order by id
      5                           ) rn
      6       , rowid rid
      7    from x) x_orig
      8   on (x.rowid = x_orig.rid)
      9   when matched then
    10   update set sortorder = x_orig.rn
    11  /
    3 rows merged.
    SQL> select *
      2    from x
      3  /
            ID DESCR  SORTORDER
             1 One            1
             4 Two            2
             6 Three          3

  • Concatenate strings from a column into a single row

    I am trying to string values from a column into a single row. I need a list of students (one row per student) with their phone number and they could have more than one number. I found a function that should do what I need but the syntax is for SQL Server, not SQL*Plus. I've tried several variations but can not come up with the correct syntax.
    This is the SQL Server version:
    CREATE FUNCTION dbo.GetPhoneList(@StudentID int)
    RETURNS varchar(500) AS
    BEGIN
    DECLARE @StringList varchar(500)
    SELECT @StringList = COALESCE(@StringList + ‘, ‘, ”) + Telephone.PhoneNumber
    FROM Telephone t
    WHERE t.StudentID = @StudentID
    IF @StringList IS NULL
    SET @StringList = ‘No Phone’
    RETURN @StringList
    END
    SQL*Plus does not like the @ symbol, so I tried taking that out. I've put semi-colons where I think they should be, but I still get various error messages. Any suggestions?
    Thanks.

    Hi,
    What you want to do is called "String Aggregation"
    You could write a PL/SQL funcrtion to do that for a specific column in a specific table, but [this page|http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2196162600402] has a couple of different generic solutions that will work on any tables and columns.
    I recommend the first soluton, the user-defined function STRAGG, which you can copy from that page.
    Once you have STRAGG installed, your query can be something like:
    SELECT     s.student_id
    ,     NVL ( STRAGG (t.phone_number)
             , 'No phone'
             )     AS phone_nums
    FROM          student          s
    LEFT OUTER JOIN     telephone     t     ON s.student_id     = t.student_id
    GROUP BY     s.student_id;On Oracle 10 (and up) you may have a similar function, WM_CONCAT (owned by WMSYS), already installed.
    WM_CONCAT is not documented, so you may not want to use it in your Production applications.
    It lokks like
    Edited by: Frank Kulash on Feb 10, 2009 6:31 PM

Maybe you are looking for

  • Booting to external H.D.D. after using C.C.C. on failing drive

    Hi folks, I'm having a severe issue with my Quad: the internal, Maxtor 250 gb HDD that came with the machine is failing. However, I can still boot to safe mode. I've used Carbon Copy Cloner to back up the disk and make it bootable, or so I thought. I

  • My client does not able to join Mac OS Server 10.6 Leopard Snow - kGotAuthe

    I am currently running Mac OS Server 10.6 Leopard Snow running on my Mac Mini. Have recently upgraded from previous version of Mac OS Server 10.5 I wanted to connect a client computer (does not matter my Mac Pro or my Mac Book - same results) to the

  • How to go back to previous page

    I have two JSP pages first.jsp and second.jsp the user starts at first.jsp and clicks the submit button which then takes the user to second.jsp where the users information is saved in a database. I want to know how to go back to first.jsp from second

  • TS1424 Unknown error 5002.  Anyone know what it means?

    When trying to signup to iTunes Match i get the error:  "Could not purchase iTunes Match.  An unknown error occurred (5002). There was an error in the iTunes Store. Please try later." I"ve been trying to 3 months now! Help ! Thank you. Ed

  • Manage AIR-AP1262N with WLC 5508

    hello, is it possible to manage a air-ap1262n with a controller like wlc 5500 or wlc 2500? the official cisco support could not answer me this question for sure. i have found this old guide to upgrade ap´s to lap´s, but there is hothing about the 126