What is a efficient SQL for this query ?

Hi,
I am using 9.2 database. Suppose I am having following 2 tables
Table p having only one column i.e. 'a'. Values in this column are
a1
b1
c1
d1
Table Q having three columns a, b, c
a1, 1, 100
a1, 2, 50
b1, 1, 30
b1, 2, 40
d1, 2, 90
Table Q can be joined only using column a.
Table Q can have multiple or no records for column a in table p. Based on above sample data, I want following output
a1, 100, 50
b1, 30, 40
c1
d1, 90
Kindly tell be how can I achive this in most efiicient way !!!
thanks & regards
PJP

I only have you two tracks about how do it.
If you want all the columns from p with or wihout q you have to do:
11:35:58 SQL> l
1 select p.*, q.*
2 from p,q
3* where p.a = q.a (+)
11:37:27 SQL> /
For change the order of the colums for rows you can see the url, the are more examples like that only need to search "columns for rows" in this forums.
Anyway:
with rt as
select 'a1' a, 1 b, 100 c from dual union
select 'a1', 2, 50 from dual union
select 'b1', 1, 30 from dual union
select 'b1', 2, 40 from dual union
select 'd1', 2, 90 from dual)
--select * from rt
select a, decode('1','0','0',rtrim(xmlagg(xmlelement(b, b || ',')).extract('//text()'),',')) b
, decode('1','0','0',rtrim(xmlagg(xmlelement(c, c || ',')).extract('//text()'),','))
from rt
group by a
Message was edited by:
cth
Other way:
select a, ltrim(b,',') as b, ltrim(c,',') as c
from (
select row_number() over (partition by a order by length(b) desc) as rn, a, b,c
from (select a, sys_connect_by_path(b, ',') as b,
          sys_connect_by_path(c, ',') as c
from (
select row_number() over (partition by a order by b) as rn, a, b,c
from rt) y
connect by rn = prior rn + 1 and prior a = a
start with rn = 1
where rn = 1
Message was edited by:
cth

Similar Messages

  • How to write SQL for this query

    Hi, All
    I have table which sample data are shown below
    CLM_NO. CLM_RUN PARTY PAY_CD
    2006213103246      2006085483      PA010193 3CO11
    2006213103246      2006085483 PA010193 3CO17
    2006213103246      0000000000 PA084113 2CO11
    2006213103246      0000000000 PA000001 2RK11
    2006213103246      0000000000 PA082822 3CO11
    2006213103270      0000000000 PA000001 2RK11
    2006213103270      0000000000 PA032456 3CO11
    for each clm_no , if data only have zero the report must show pay_cd minimum value(2RK11) but when clm_run have both zero and nonzero data the report will show minimum pay_cd of record that have clm_run nonzero data(3CO11)
    Thank you
    Mcka

    Hi Mcka
    Based on the example you have provided, we should have only the following two rows in the final result:
    CLM_NO. CLM_RUN PARTY PAY_CD
    2006213103246 2006085483 PA010193 3CO11
    2006213103270 0000000000 PA000001 2RK11
    The first line is displayed because even though there are 6 rows for CLM_NO 2006213103246, with a combination of zero and non-zero CLM_RUNS, we need to display the non-zero row containing the minimum PAY_CD.
    The second line is displayed because both rows have a zero CLM_RUN and we need to display the row which has the lowest PAY_CD.
    If this understanding sounds right to you then you need to create the following condition:
    RANK() OVER(PARTITION BY CLM_NO ORDER BY CLM_RUN DESC, PAY_CD ASC) = 1
    Can you follow what this is doing?
    Basically, for each CLM_NO, identified by the clause PARTITION BY CLM_NO, we are ranking the combination of CLM_RUN and PAY_CD where the CLM_RUN is sorted in high to low order and the PAY_CD is sorted in low to high order. This will cause Discoverer to allocate an ascending range of numbers starting with 1, where 1 corresponds to the row you are looking for. If we create a condition such that this whole expression equals 1 then we must display only the rows that you want, with one row being displayed per CLM_NO.
    Note: This works so long as the same CLM_NO cannot have two or more different CLM_RUN numbers where one of the higher CLM_RUNs has a lower PAY_CD than the other non-zero CLM_RUNs.
    It also makes the assumption that for a given non-zero CLM_RUN there will not be two or more identical PAY_CDs. If this condition can exist then you could exclude duplicate values from the report. If you have never done this there is a checkbox called Hide Duplicate Rows on the Layout tab of the Edit Worksheet Dialog box.
    Best wishes
    Michael

  • Is there a way to create a plan guide for this query?

    How can i create a plan guide for this query,suppose i can't change the query text:
    USE AdventureWorks2008R2;
    GO
    SET NOCOUNT ON;
    GO
    -- query plan statement starts
    DECLARE @Group nvarchar(50), @Sales money;
    SET @Group = N'North America';
    SET @Sales = 2000000;
    SET NOCOUNT OFF;
    SELECT FirstName, LastName, SalesYTD
    FROM Sales.vSalesPerson
    WHERE TerritoryGroup = @Group and SalesYTD >= @Sales;
    -- query plan statement ends
    AdventureWorks2008R2's parameterization option is simple, i want this type of query can reuse plan:
    DECLARE @Group nvarchar(50), @Sales money;
    SET @Group = N'Other Country';
    SET @Sales = 88;
    SET NOCOUNT OFF;
    SELECT FirstName, LastName, SalesYTD
    FROM Sales.vSalesPerson
    WHERE TerritoryGroup = @Group and SalesYTD >= @Sales;
    I tried many times ,but it didn't work:
    declare @xml nvarchar(max) -- the plan i want to reuse
    set @xml = (select cast (query_plan as nvarchar(max)) 
    from sys.dm_exec_query_plan (0x060006001464570B405D92620200000001000000000000000000000000000000000000000000000000000000))
    -- create plan guide 
    exec sp_create_plan_guide 
    @name ='Test'
    ,@stmt=N'SELECT FirstName, LastName, SalesYTD
    FROM Sales.vSalesPerson
    WHERE TerritoryGroup = @Group and SalesYTD >= @Sales;'
    ,@type =N'sql'
    ,@params =N'@Group nvarchar(50), @Sales money'
    ,@hints = @xml;
    Thanks.

    I guess you don't wanna fire these queries "adhoc" but prepared instead to reuse the plan:
    exec sp_executesql N'SELECT FirstName, LastName, SalesYTD FROM Sales.vSalesPerson WHERE TerritoryGroup = @Group and SalesYTD >= @Sales',
    N'@Group nvarchar(50), @Sales money', N'Other Country',88
    exec sp_executesql N'SELECT FirstName, LastName, SalesYTD FROM Sales.vSalesPerson WHERE TerritoryGroup = @Group and SalesYTD >= @Sales',
    N'@Group nvarchar(50), @Sales money', N'North America',2000000
    Bodo Michael Danitz - MCT, MCITP - free consultant - performance specialist - www.sql-server.de

  • What r the tables used for this report.

    hi all..
    i am a fresher for ABAP. i need the help.
    what r the tables used for this report.
    Reports provide pending order details according to Material wise and customer wise for particular month.
    thanks in advance
    RK.Ashokkumar.

    Hi Ashok,
    this is easy to do.
    Open Two SAP Screen with same user ID.
    Run SQL trace using ST05 transaction.Open ST05 transaction in One and make
    Trace on ,Run the report in another screen.
    Once report run is over.End the trace process and click on display trace in same ST05 transaction.There is a click button on ST05 Transaction screen to start trace
    process,End trace process and Display track process.
    The SQL trace will  give you all the table details which is used in that particular report.
    You have not mentioned about the report name so I have suggested this way.
    regards,nishant
    Please reward if this helps

  • Any room for improvement for this query? Explain Plan attached.

    Is there any room for improvement for this query? Table stats are up-to-date. Any suggestions Query rewrite, addition of indexes,...etc ??
    select sum(CONF
                 when (cd.actl_qty - cd.total_alloc_qty - lsd.Q < 0) then
                  0
                 else
                  cd.actl_qty - cd.total_alloc_qty - lsd.Q
               end)
      from (select sum(reqd_qty) as Q, ITEM_ID as ITEM
              from SHIP_DTL SD
             where exists (select 1
                      from CONF_dtl
                     where CONF_nbr = '1'
                       and ITEM_id = SD.ITEM_id)
             group by ITEM_id) lsd,
           CONF_dtl cd
    where lsd.ITEM = cd.ITEM_id
       and cd.CONF_nbr = '1'Total number of rows in the tables involved
    select count(*) from CONF_DTL;
      COUNT(*)
       1785889
    select count(*) from shp_dtl;
      COUNT(*)
        286675
      Explain Plan
    PLAN_TABLE_OUTPUT
    Plan hash value: 2325658044
    | Id  | Operation                           | Name               | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                    |                    |     1 |    39 |     4  (25)| 00:00:01 |
    |   1 |  SORT AGGREGATE                     |                    |     1 |    39 |            |          |
    |   2 |   VIEW                              |                    |     1 |    39 |     4  (25)| 00:00:01 |
    |   3 |    HASH GROUP BY                    |                    |     1 |   117 |     4  (25)| 00:00:01 |
    |   4 |     TABLE ACCESS BY INDEX ROWID     | SHIP_DTL           |     1 |    15 |     1   (0)| 00:00:01
    |   5 |      NESTED LOOPS                   |                    |     1 |   117 |     3   (0)| 00:00:01 |
    |   6 |       MERGE JOIN CARTESIAN          |                    |     1 |   102 |     2   (0)| 00:00:01 |
    |   7 |        TABLE ACCESS BY INDEX ROWID  | CONF_DTL           |     1 |    70 |     1   (0)| 00:00:01 |
    |*  8 |         INDEX RANGE SCAN            | PK_CONF_DTL        |     1 |       |     1   (0)| 00:00:01 |
    |   9 |        BUFFER SORT                  |                    |     1 |    32 |     1   (0)| 00:00:01 |
    |  10 |         SORT UNIQUE                 |                    |     1 |    32 |     1   (0)| 00:00:01 |
    |  11 |          TABLE ACCESS BY INDEX ROWID| CONF_DTL           |     1 |    32 |     1   (0)| 00:00:01 |
    |* 12 |           INDEX RANGE SCAN          | PK_CONF_DTL        |     1 |       |     1   (0)| 00:00:01 |
    |* 13 |       INDEX RANGE SCAN              | SHIP_DTL_IND_6 |     1 |       |     1   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       8 - access("CD"."CONF_NBR"='1')
      12 - access("CONF_NBR"='1')
      13 - access("ITEM_ID"="SD"."ITEM_ID")
           filter("ITEM_ID"="CD"."ITEM_ID")

    Citizen_2 wrote:
    Is there any room for improvement for this query? Table stats are up-to-date. Any suggestions Query rewrite, addition of indexes,...etc ??You say that the table stats are up-to-date, but is the following assumption of the optimizer correct:
    select count(*)
    from CONF_dtl
    where CONF_nbr = '1';Does this query return a count of 1? I doubt that, but that's what Oracle estimates in the EXPLAIN PLAN output. Based on that assumption you get a cartesian join between the two CONF_DTL table instances, and the result - which is still expected to be one row at most - is then joined to the SHIP_DTL table using a NESTED LOOP.
    If above assumption is incorrect, the number of rows generated by the cartesian join can be tremendous rendering the NESTED LOOP operation quite inefficient.
    You can verify this by using the DBMS_XPLAN.DISPLAY_CURSOR function together with the GATHER_PLAN_STATISTICS hint, if you're already on 10g or later.
    For more information regarding the DISPLAY_CURSOR function, see e.g. here: http://jonathanlewis.wordpress.com/2006/11/09/dbms_xplan-in-10g/
    It will show you the actual cardinalities compared to the estimated cardinalities.
    If the estimate of the optimizer is incorrect, you should find out why. There still might be some issues with the statistics, since this is most obvious reason for incorrect estimates.
    Are your index statistics up-to-date?
    Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • What’s the best practice for this scenario?

    Hi,
    My users want the ability to change the WHERE and/or ORDER BY clause at runtime. They may define user preferences on each screen ( which is bind to a view object). They want to see the same records based on WHERE/ORDER BY defined on the last visit. That is why I keep the users preferences and load the screen based on that, using :
    View.setWhereClause(...);
    View.setOrderByClause(...);
    View.executeQuery();
    This works good when only one user working with the application but faced low performance when more than one user working with the application.
    What are the points to increase the performance and what is the best practice for this scenario?
    Thanks for your help in advance.

    Sung,
    I am talking only about 2 users in my testing. I am sure i missed something but could not recognize that.
    This page is my custom query page including a tag to instantiate app module in stateful mode at the top <jbo:ApplicationModule..> and a tag to instantiate data source <jbo:Datasource...> and release tag at the bottom <jbo:ReleasePageResources..> and some java code in the middle(body). The java code constructed the query statement and then fires the query to set the view object based on the query statement using the above methods.
    So, I am facing very slow performance(speed) when two clients load this page at the same time. Looks like the entire application locks for others when one client load this page and fire the query. i realized the battle neck is where executeQuery() is executing.
    what do you think.
    Thanks in advance for your comments.

  • I need solution for this query

    hi all,
    could anyone please send me solution for this query these are the database tables am having
    TABLE NAME :USERS
    ATTRIBUTES
    UNAME
    PASSWORD
    GROUPNAME
    TABLE NAME:GROUPS
    ATTRIBUTES
    GROUPID
    GROUPNAME
    my requirement is that i need 2 acces the groupname of a particular user and the reamining groups to which i doesn't belong in A SINGLE QUERY
    my result needs to be like this
    Authorised group
    consultant
    UNAuthorised groups
    sales
    vender
    recruiter
    admin
    if any body got the solution please send

    hi All,
    I have 3 tables 1)PREVILEGES (groupname, previleges(values y or n only))
    2)GROUPS (groupid, groupname)
    3) USERS (uname, groupname).
    Here each user belongs to one group, each user hav a default previlege means example if user is consutant then he can access only consultant group. Means default previlege will be used. For default previleges, there is no record in Previleges table.
    The Problem is that, I need to reterive the groupname from users which de doesn't belong as well as his previleges from previleges, If there is no values in previleges in the table it should return n. or value what is therey.
    the different groups are
    SALES,CONSULTANT,VENDER,RECRUTER,ADMIN

  • Internal Error - Unable to generate SQL for this Scheduled Workbook

    I am encountering the following error when loading the results of a Scheduled Workbook;
    Internal Error - Unable to generate SQL for this Scheduled Workbook (If you scheduled this workbook using a previous version of Discoverer, please reschedule and re-open)
    This only happens for one of the scheduled workbooks and I am struggling to find an explanation to the problem. There are no reference to database links in the workbook so I can rule that out as a cause.
    Does anyone have any suggestions to what might be causing the problem?
    Many thanks
    Stewart

    Hi,
    The version is OracleBI Discoverer Plus Version 10.1.2.48.18. Do you think this has anything to do with it?If you are on this version, then you have the recommended patches applied.
    Did you try to reschedule the workbook and see if this helps in resolving the issue?
    I would suggest you enable server logging as this may help in collecting more details about the error.
    Note: 403689.1 - How To Generate Discoverer 10g (10.1.2) Session Server Logs In Text Format
    https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=403689.1
    Regards,
    Hussein

  • I have problems in the initiation of the Encore process when opening presents the following error message : "Encore CS6 Cannot Run in Non-Royalty Serialized".... What is the best solution for this problem ?

    Help Me.
    What is the best solution for this problem ?

    Encore is activated when you activate Premiere Pro... so, as Stan asked, how did you install P-Pro?
    Ask for serial number http://forums.adobe.com/thread/1234635 has a FAQ link
    -and a fix for Encore http://forums.adobe.com/thread/1421765?tstart=0 in reply #7
    -plus more Encore http://helpx.adobe.com/encore/kb/cant-write-image-fie-larger1.html

  • Hi, I m using an iPhone 4 and my yahoo push email was working just fine but for the last few days I am experiencing some problem that is the emails are not getting pushed , I have to manually fetch the mails. So what could be the reason for this....

    Hi, I m using an iPhone 4 and my yahoo push email was working just fine but for the last few days I am experiencing some problem that is the emails are not getting pushed , I have to manually fetch the mails. So what could be the reason for this.....I have set the email setting to "push" mode. Moreover I can't edit the mail server address ....current it's on Yahoo SMTP server

    Will it get rectified and restored...if so after how long. What could be the reason for such outage kindly share,  as I am facing real problem because of this...

  • What are the tables used for this Report

    hi all..
    i am a fresher for ABAP. i need the help.
    what r the tables used for this report.
    Reports provide pending order details according to Material wise and customer wise for particular month.
    thanks in advance
    RK.Ashokkumar.
    9994262112.

    hi
    good
    try with these tables,
    MARA
    KNA1
    thanks
    mrutyun^

  • HT1222 What is a pass code,for this next up date.never been asked that before

    What's the pass code for this next update.never been asked that in the past

    The passcode you need to enter is the passcode you set on your device. It is the passcode that you enter when you turn on your iPad or awaken it from sleep after and Auto lock.
    If you do not know or remember your password and did not store it somewhere then you will have to restore your device.
    http://support.apple.com/kb/HT1212

  • My requirement is to update 3 valuesets daily based on data coming to my staging table. What is the API used for this and how to map any API to our staging table? I am totally new to oracle and apps. Please help. Thanks!

    My requirement is to update 3 valuesets daily based on data coming to my staging table. What is the API used for this and how to map any API to our staging table? I am totally new to oracle and apps. Please help. Thanks!

    Hi,
    You could use FND_FLEX_LOADER_APIS.UP_VALUE_SET_VALUE to upload them from staging table (I suppose you mean value set values...).
    You can find a sample scripts if you google around.
    What do you mean "how to map any API to our staging table" ?
    You should do at least the following mapping (which column(s) in the staging table will provide these information):
    - the 3 value sets name which you're going to update/upload (I suppose these are existing value sets or which have been already created)
    - the value set values and  description
    Try to start with something and if there is any issues the community could then help... but for the time being with the description of the problem you have provided, that's the best I can do...

  • JZ0R2 -- No result set for this query

    hi,
    I'm using this code to update records in the database:
    facsk = myArray[ctr];
    query = 'excute dp_autogeo_accept" + facsk;
    stmt.executeQuery(query);
    No records are returned so I'm not sending anything to a result set or trying to read the next string. I get this error: JZ0R2: No result for this query. I'm not sure why the original developer chose to use executeQuery but I've also tried stmt.updateQuery and got this error.
    Can someone help me?

    hi,
    I'm using this code to update records in the
    database:
    facsk = myArray[ctr];
    query = 'excute dp_autogeo_accept" +
    _accept" + facsk;
    stmt.executeQuery(query);
    No records are returned so I'm not sending anything
    to a result set or trying to read the next string. I
    get this error: JZ0R2: No result for this
    query. I'm not sure why the original developer
    chose to use executeQuery but I've also tried
    stmt.updateQuery and got this error.
    Can someone help me?when you're executing a query that has no result set use stmt.executeUpdate() instead of stmt.executeQuery()

  • I have an ipod shuffle 1st generation it will work if i connect it to my usb port in car or on computer but i can not get it to work using just headphones what coud be the reason for this

    I have an ipod shuffle 1st generation. it will work ousing usb port in car or on computer but i can not get it to play using headphones. what would be the reason for this.

    Sorry for  the typos, I hope my message still gets across!

Maybe you are looking for