Single query

Hello to all
I have the following trigger
          SELECT COUNT(*) INTO ESISTE FROM A_PAZIENTI_NPRELIEVO  PNP
          WHERE K_CODE  =  :new.K_CODE
          AND  ANNO     = :new.ANNO
          AND TIPORD    = :new.TIPORD
          AND DATA_R    = TRUNC(:new.DATA_PRENOTATA);
          IF ESISTE = 0 THEN
               SELECT NVL(LPAD(TO_CHAR(MAX(to_number(substr(NPRELIEVO,8,3))) + 1),3,'0'),'001')
               INTO NPRELIEVOC
               FROM A_PAZIENTI_NPRELIEVO
               WHERE K_CODE  =  :new.K_CODE
               AND  ANNO     = :new.ANNO
               AND TIPORD    = :new.TIPORD
               AND DATA_R    = TRUNC(:new.DATA_PRENOTATA);
               NPRELIEVOT :=     TO_CHAR(:new.ANNO)||to_char(TRUNC(:new.DATA_PRENOTATA),'DDD') ||NPRELIEVOC;               
               insert into A_PAZIENTI_NPRELIEVO VALUES (:new.K_CODE,:new.TIPORD,:new.ANNO,TRUNC(:new.DATA_PRENOTATA),NPRELIEVOT);
        END IF;How can I change to create a single query that is, no two select (first to see if exist and second for get max)
a kind of
Insert into from
select
Thanks for any help

Boneist wrote:
ETA: emoticon issues? What issues?! *{;-)You mean we've all got to start wearing hats?
{|:-)                                                                                                                                                                                                                                                                                       

Similar Messages

  • How to use multiple hierarchies for a single char in single query

    Hi,
    Is there any way that we can use multiple hierarchies for a single char in single query. I tried and it just allows me to select one hierarchy even if I use hierarchy variable.
    I have a requirement where user wants to see information related to a cost center with different cost center groups in different hierarchies (every year has different cost center group hierarchies).
    Suppose I want to see information related to a cost center from year 2001-2004.in these four year cost center may have been associated to different groups depending upon that year hierarchy. How can I do that?
    Thanks
    Jona

    Nope. Now way to do this.
    There is always just one hierarchy assigned to a characteristic. And even if the hierarchy was time dependent, it only reads it for one key date and not according to transaction data.
    Regards,
    Beat

  • Multiple databases in a single query

    I need to query multiple databases in a single query.
    e.g.
    Database d1 contains table t1 with column id
    Database d2 contains table t2 with column id
    I need a query like
    SELECT * FROM t1, t2 WHERE t1.id = t2.id;
    is this possible in jdbc? if yes can anyone help with some sample code?
    thanks,
    Ashish Saraf

    It is not possible using the JDBC API to query tables in two or more databases using a single query. The reason is that a JDBC Connection is made to a single data source.
    However, some databases support the idea of federations or linked tables. What you do is inside the database manager link or federate a table that is present in another DBMS. Then, pose a single JDBC query to the one DBMS which will have its own table and links to the external tables.
    Another approach is to use a special JDBC driver with a built-in integration engine that will perform a query across multiple databases. In effect, the system poses separate queries to the different databases and integrates and joins the data together for you automatically on the client-side. That is much easier than doing it yourself in code, but that is also possible for simple queries.
    As part of my research program, we have released a shareware version of the UnityJDBC driver that can query multiple databases using a single SQL query. For more information, see:
    http://www.unityjdbc.com
    http://www.cs.uiowa.edu/~rlawrenc/research/projects.html
    Sincerely,
    Dr. Ramon Lawrence
    Assistant Professor
    Department of Computer Science
    University of Iowa
    [email protected]

  • 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

  • How to make the query in one single query? No Union please....

    Hi,
    I have sets of around 18 queries which is finding counts in many scenarios. I wanted to have a single query for this. which diplays the result in a single row.Is there a way , I heared analytical functions are good options ,but I am new to Oracle . Please help me.
    select count(*) total_count from emp; --100
    select coun(*) MGR_count from emp where job='MGR'-- 10
    select count(*) dept_count from emp where deptno in(10 ,20)-- 75
    output..
    TOTAL_COUNT     MGR_COUNT      DEPT_COUNT
    100                                   10             75
    Thanks

    This:
    select count(*) total_Count
          ,count(decode(job,'MGR',1,null)) mgr_count
          ,count(case when deptno in (10,20) then
                   1
                 else
                   null
                 end
                ) dept_count
    from emp;
    untested

  • Multiple conditin on a single column in a single query

    i want to select data from the table using diff conditions on a single column
    for eg:
    i need emp details like whose having empno as 5-15,19-45,50-89 ..etc this how can i give a condition in a single query
    we can use in or between for 2 or 3 conditions but i have plenty off like this

    Hi,
    848525 wrote:
    i want to select data from the table using diff conditions on a single column
    for eg:
    i need emp details like whose having empno as 5-15,19-45,50-89 ..etc this how can i give a condition in a single query
    we can use in or between for 2 or 3 conditions but i have plenty off like thisYou can use OR for any number of conditions; it works the same for 4 or more.
    You could also put the ranges into a table (or a sub-query, as shown below) and join:
    WITH     empno_ranges     AS
         SELECT     3000 AS low_val, 5000 AS high_val  FROM dual  UNION ALL
         SELECT     7000,           7499               FROM dual  UNION ALL
         SELECT     7500,           7599               FROM dual  UNION ALL
         SELECT     7800,           7899               FROM dual
    SELECT       r.*
    ,       COUNT (e.empno)     AS emp_cnt
    FROM            empno_ranges     r
    LEFT OUTER JOIN     scott.emp     e  ON  e.empno  BETWEEN r.low_val
                                                 AND     r.high_val
    GROUP BY  r.low_val, r.high_val
    ORDER BY  r.low_val
    ;Output:
    LOW_VAL   HIGH_VAL    EMP_CNT
       3000       5000          0
       7000       7499          2
       7500       7599          2
       7800       7899          3

  • All selected 'n' consecutive rows in retrieved in a single query

    hello,
    I have table T with 50,000 rows
    create table T
    (student_id number,
    class_id number,
    quiz_id number,
    marks number)
    some sample rows like
    INSERT INTO T VALUES (1,1, 1, 50);
    INSERT INTO T VALUES (2,2, 2, 40);
    INSERT INTO T VALUES (3,1, 3, 34);
    INSERT INTO T VALUES (1,1, 4, 10);
    INSERT INTO T VALUES (1,1, 5, 30);
    INSERT INTO T VALUES (1,1, 6, ‘29);
    INSERT INTO T VALUES (3,2, 7, 34);
    INSERT INTO T VALUES (3,2, 8, 33);
    INSERT INTO T VALUES (3,2, 9, 56);
    INSERT INTO T VALUES (1,1, 7, 90);
    INSERT INTO T VALUES (2,2, 8, 0,);
    INSERT INTO T VALUES (1,1, 8, 80);
    INSERT INTO T VALUES (2,2, 8, 65);
    INSERT INTO T VALUES (1,1, 9, ‘34);
    INSERT INTO T VALUES (2,2, 9, 11);each student belongs to one class_id. each student participates in many quizes. each quiz has its unique id. each student can appear once in a quiz_id
    I am doing the below analysis and query:
    1. with below query I am finding which student_id had most marks in any 3 successive quizes (see the 3-1 part below) in the query..
    SELECT QUIZ_ID,
          STUDENT_ID,
    SUM (MARKS) OVER (PARTITION BY STUDENT_ID ORDER BY QUIZ_ID1
    RANGE BETWEEN CURRENT ROW AND (3-1) FOLLOWING) consecMARKS , MARKS   FROM
          (SELECT QUIZ_ID,
            STUDENT_ID,
            MARKS,
          ROW_NUMBER() OVER (PARTITION BY STUDENT_ID ORDER BY T.QUIZ_ID) QUIZ_ID1
          FROM T
          WHERE MARKS IS NOT NULL
          ORDER BY 1
        ORDER BY 3 DESC
    SQL> /
       QUIZ_ID STUDENT_ID CONSECMARKS
             7          1         170
             6          1         166
             8          1         129
             5          1         106
             8          3          89
             8          2          76
             3          3          68
             7          3          67
             8          2          65
             1          1          60
             9          3          56
       QUIZ_ID STUDENT_ID CONSECMARKS
             9          1          49
             2          2          40
             4          1          40
             9          2          11
    15 rows selected.With above query, I can play around and find for any 'n' number of consecutive quizes, like marks in 2 consecutives quizes, 3, 4 and so on but for each 'n' value I've to run a seperate query mentioning (2-1) or (3-1) or (4-1) and so on..
    since my table is big and there are about 400 quizes so what I want to find out is for each 'n' consecutive quiz (from 1 to 400) which student had most marks for each consecutie 'n' quiz. Like in 1 (consecutive) quiz which student had the highest marks and then 2 conseuctive quiz who had most marks and then in 3 consecutive quiz who had most marks and so on till 400 consecutive quiz who had most marks... rather than running query for each 'n' value seperately i want a single query that can give me a summary of most marks in each n consecutive quizes...
    my sample output is:
    Nth consecutive quiz     student_id    sum(marks)
    1                        1              90
    2                        1              170
    3                        1              246
    4
    100
    200
    300
    400                      ?              ?   Is this possible to get the above output from one single query? If there are two or more students with equal most marks for any 'n' conseutive quizes then both should come in the summary.
    Hope I have been able to put up my question clearly.
    regards
    Ramis

    Something like:
    SELECT  N,
            QUIZ_ID,
            STUDENT_ID,
            SUM(MARKS) OVER (PARTITION BY N,STUDENT_ID ORDER BY QUIZ_ID1 RANGE BETWEEN CURRENT ROW AND (N-1) FOLLOWING) consecMARKS,
            MARKS
      FROM  (SELECT  QUIZ_ID,
                     STUDENT_ID,
                     MARKS,
                     ROW_NUMBER() OVER (PARTITION BY STUDENT_ID ORDER BY T.QUIZ_ID) QUIZ_ID1
               FROM  T
               WHERE MARKS IS NOT NULL
             SELECT  LEVEL N
               FROM  DUAL
               CONNECT BY LEVEL <= (
                                    SELECT  COUNT(DISTINCT QUIZ_ID)
                                      FROM  T
        ORDER BY N,
                 consecMARKS DESC
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             1          7          1          90         90
             1          8          1          80         80
             1          8          2          65         65
             1          9          3          56         56
             1          1          1          50         50
             1          2          2          40         40
             1          9          1          34         34
             1          7          3          34         34
             1          3          3          34         34
             1          8          3          33         33
             1          5          1          30         30
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             1          6          1          29         29
             1          9          2          11         11
             1          4          1          10         10
             1          8          2           0          0
             2          7          1         170         90
             2          6          1         119         29
             2          8          1         114         80
             2          8          3          89         33
             2          8          2          76         65
             2          3          3          68         34
             2          7          3          67         34
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             2          8          2          65          0
             2          1          1          60         50
             2          5          1          59         30
             2          9          3          56         56
             2          2          2          40         40
             2          4          1          40         10
             2          9          1          34         34
             2          9          2          11         11
             3          7          1         204         90
             3          6          1         199         29
             3          5          1         149         30
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             3          7          3         123         34
             3          8          1         114         80
             3          2          2         105         40
             3          3          3         101         34
             3          1          1          90         50
             3          8          3          89         33
             3          8          2          76         65
             3          8          2          76          0
             3          4          1          69         10
             3          9          3          56         56
             3          9          1          34         34
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             3          9          2          11         11
             4          6          1         233         29
             4          5          1         229         30
             4          7          1         204         90
             4          4          1         159         10
             4          3          3         157         34
             4          7          3         123         34
             4          1          1         119         50
             4          2          2         116         40
             4          8          1         114         80
             4          8          3          89         33
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             4          8          2          76          0
             4          8          2          76         65
             4          9          3          56         56
             4          9          1          34         34
             4          9          2          11         11
             5          5          1         263         30
             5          4          1         239         10
             5          6          1         233         29
             5          1          1         209         50
             5          7          1         204         90
             5          3          3         157         34
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             5          7          3         123         34
             5          2          2         116         40
             5          8          1         114         80
             5          8          3          89         33
             5          8          2          76          0
             5          8          2          76         65
             5          9          3          56         56
             5          9          1          34         34
             5          9          2          11         11
             6          1          1         289         50
             6          4          1         273         10
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             6          5          1         263         30
             6          6          1         233         29
             6          7          1         204         90
             6          3          3         157         34
             6          7          3         123         34
             6          2          2         116         40
             6          8          1         114         80
             6          8          3          89         33
             6          8          2          76          0
             6          8          2          76         65
             6          9          3          56         56
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             6          9          1          34         34
             6          9          2          11         11
             7          1          1         323         50
             7          4          1         273         10
             7          5          1         263         30
             7          6          1         233         29
             7          7          1         204         90
             7          3          3         157         34
             7          7          3         123         34
             7          2          2         116         40
             7          8          1         114         80
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             7          8          3          89         33
             7          8          2          76          0
             7          8          2          76         65
             7          9          3          56         56
             7          9          1          34         34
             7          9          2          11         11
             8          1          1         323         50
             8          4          1         273         10
             8          5          1         263         30
             8          6          1         233         29
             8          7          1         204         90
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             8          3          3         157         34
             8          7          3         123         34
             8          2          2         116         40
             8          8          1         114         80
             8          8          3          89         33
             8          8          2          76          0
             8          8          2          76         65
             8          9          3          56         56
             8          9          1          34         34
             8          9          2          11         11
             9          1          1         323         50
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             9          4          1         273         10
             9          5          1         263         30
             9          6          1         233         29
             9          7          1         204         90
             9          3          3         157         34
             9          7          3         123         34
             9          2          2         116         40
             9          8          1         114         80
             9          8          3          89         33
             9          8          2          76          0
             9          8          2          76         65
             N    QUIZ_ID STUDENT_ID CONSECMARKS      MARKS
             9          9          3          56         56
             9          9          1          34         34
             9          9          2          11         11
    135 rows selected.
    SQL> SY.

  • Is it possible to combine 2 different reports in a single Query?

    Dear All,
    What am I working at?
    I produced a Query for Debtors Aged Analysis which mimics the Official SAP B1 8.8 Aging Report.
    It ages the outstanding invoices by Posting Date ( RefDate  in JDT1)
    I also made another Report which ages outstanding amounts by Document Date simply by replacing all RefDate by TaxDate
    They give different answers if Posting Date is different from Document Date, e.g a manual invoice dated 5 Jun 2011 is posted on 2 Jul 2011.
    What I want to do?
    My idea is to produce a SINGLE QUERY which will generate either Aging depending on settings:
        (a) A Debtors Aging by Posting Date
        (b) A Debtors Aging by Document Date
    I declare 2 variables:
    (a) @refdt  is [%1] and represents Posting Date (JDT1 RefDate)
    (b) @taxdt  is [%2] and represents Document Date (JDT1 TaxDate)
    When the Query is run, the foll dialog appears:
    Query - Selection Criteria
    Posting Date             Equal .......
    Document Date            Equal .......
    OK   Cancel
    We are expected to fill in only 1 date and leave the other blank, and Query will generate the required report .
    What is my problem?
    Query runs smoothly, but amounts in the Balance column does not get analyzed in the Age brackets: Current / 1 Mth Ago / etc
    I think I know where's the problem
    I am assuming (wrongly) that if we don't fill one date field, the query returns NULL for that variable. In fact, it appears to return GetDate().
    Help
    Can anybody help me put the correct commands so that all my balances are correctly analysed in the respective age buckets?
    Thanks
    Leon Lai
    Here's a simplified SQL:
    Tables  :
          JDT1   T0  = Journal Entry - Rows
          OCRD T1 = Business Partner
          OCPR T2 = Contact Person
          OJDT  T3  = Journal Entry - Header
          OINV   T4  = A/R Invoices - Header
          ORIN   T5  - A/R Credit Memo - Header
    declare @refdt date
    declare @taxdt date
    set @refdt
    /*Select 1 from jdt1 t where t.RefDate*/ = [%1]
    set @taxdt
    /*Select 1 from jdt1 w where w.TaxDate*/ = [%2]
    SELECT
    'company1' AS 'Company',
    T1.CardCode  AS 'BP Code',
    T2.Notes2 AS 'BP Name',
    T0.RefDate AS 'Pstg Dt',
    T0.TaxDate AS 'Doc Dt',
    CASE
             WHEN T0.TransType = 13 THEN 'IN'
             WHEN T0.TransType = 14 THEN 'CN'
             WHEN T0.TransType = 30 THEN 'JE'
             WHEN T0.TransType = 24 THEN 'RC'
             WHEN T0.TransType = 46 THEN 'PS'
             ELSE 'Error ! ! !'
    END AS 'Doc Type',
    T0.Ref1 'Doc. Number',
    ISNULL(T0.FCCurrency, ' - ') AS 'Ccy',
    (T0.FCDebit - T0.FCCredit) AS 'Orig. F.Ccy',
    (T0.BalFcDeb - T0.BalFcCred) AS 'Bal. F. Ccy',
    (T0.Debit - T0.Credit) AS 'Orig. Rs',
    (T0.BalDueDeb - T0.BalDueCred) AS 'Bal. Rs',
    /* ########################  PROBLEM is here   ################## */
    CASE
                   WHEN (@refdt is not null) and (@taxdt is null)
                   THEN ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred
                   WHERE DateDiff(mm, T0.RefDate, @refdt) = 0 ) ,0)
                   WHEN (@refdt is null) and (@taxdt is not null)
                   THEN ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred
                    WHERE DateDiff(mm, T0.TaxDate, @taxdt) = 0 ) ,0)
    END AS 'Current Mth', 
    CASE
                   WHEN (@refdt is not null) and (@taxdt is null)
                   THEN ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred
                   WHERE DateDiff(mm, T0.RefDate, @refdt) = 1 ) ,0)
                   WHEN (@refdt is null) and (@taxdt is not null)
                   THEN ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred
                    WHERE DateDiff(mm, T0.TaxDate, @taxdt) = 1 ) ,0)
    END AS '1 Mth Ago'
    /* Similarly for other age buckets  */
    FROM company1.dbo.JDT1 T0
    INNER JOIN company1.dbo.OCRD T1 ON T0.ShortName = T1.CardCode
    LEFT OUTER JOIN company1.dbo.OCPR T2 ON T1.CardCode = T2.Cardcode
    LEFT OUTER JOIN company1.dbo.OJDT T3 ON T0.TransID = T3.TransID
    LEFT OUTER JOIN company1.dbo.OINV  T4 ON T3.TransID = T4.TransID
    LEFT OUTER JOIN company1.dbo.ORIN  T5 ON T3.TransID = T5.TransID
    WHERE
    T1.CardType = 'C' and Balance != 0
    and (T0.BalDueDeb - T0.BalDueCred) != 0

    HI
    I generate the next aged analysis
    CREATE PROCEDURE [dbo].[Aged_Analysis] (@end datetime,@Client VarChar (20)) AS
    BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Declare @SAPUNION Table (SN VarChar(50), TransId Int, ReconSum Decimal(19,2), DebHab VarChar(1),
                                       Linea Int)
    insert into @SAPUNION
    SELECT X0.ShortName 'SN', X0.TransId 'TransId', SUM(X0.ReconSum)'ReconSum', X0.IsCredit 'DebHab', X0.TransRowId 'Linea'
                FROM ITR1 X0
                INNER JOIN OITR X1 ON X1.ReconNum = X0.ReconNum
                WHERE X1.ReconDate <= @end  AND X1.CancelAbs = ''
                GROUP BY X0.ShortName, X0.TransId, X0.IsCredit, X0.TransRowId
    SELECT T0.CardCode, T0.CardName,T0.Address,T0.CreditLine,
    T1.TransId , T4.BaseRef , T1.Ref2 , T1.RefDate, T1.DueDate,
    CASE
          WHEN T3.DebHab = 'D'  THEN T1.Debit-T1.Credit-T3.ReconSum
          WHEN T3.DebHab = 'C'  THEN T1.Debit-T1.Credit+T3.ReconSum
          ELSE (T1.Debit-T1.Credit)
    END 'Balance',
    CASE
           when DateDiff(Day,t1.RefDate,GetDate()) <= 30 and T3.DebHab = 'D'  then T1.Debit-T1.Credit-T3.ReconSum
           when DateDiff(Day,t1.RefDate,GetDate()) <= 30 and T3.DebHab = 'C'  then T1.Debit-T1.Credit+T3.ReconSum
           when DateDiff(Day,t1.RefDate,GetDate()) <= 30 then (T1.Debit-T1.Credit) end '0-30 dias',
    CASE
           when DateDiff(Day,t1.refdate,GetDate()) between 31 and 45 and T3.DebHab = 'D'  then T1.Debit-T1.Credit-T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) between 31 and 45 and T3.DebHab = 'C'  then T1.Debit-T1.Credit+T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) between 31 and 45 then (T1.Debit-T1.Credit) end '31-45 dias',
    CASE
           when DateDiff(Day,t1.refdate,GetDate()) between 46 and 60 and T3.DebHab = 'D'  then T1.Debit-T1.Credit-T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) between 46 and 60 and T3.DebHab = 'C'  then T1.Debit-T1.Credit+T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) between 46 and 60 then (T1.Debit-T1.Credit) end '46-60 dias',
    CASE
           when DateDiff(Day,t1.refdate,GetDate()) between 61 and 75 and T3.DebHab = 'D'  then T1.Debit-T1.Credit-T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) between 61 and 75 and T3.DebHab = 'C'  then T1.Debit-T1.Credit+T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) between 61 and 75 then (T1.Debit-T1.Credit) end '61-75 dias',
    CASE
           when DateDiff(Day,t1.refdate,GetDate()) BETWEEN 76 AND 89 and T3.DebHab = 'D'  then T1.Debit-T1.Credit-T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) BETWEEN 76 AND 89 and T3.DebHab = 'C'  then T1.Debit-T1.Credit+T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) BETWEEN 76 AND 89 then (T1.Debit-T1.Credit) end '76-89 dias',
    CASE
           when DateDiff(Day,t1.refdate,GetDate()) >90 and T3.DebHab = 'D'  then T1.Debit-T1.Credit-T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) >90 and T3.DebHab = 'C'  then T1.Debit-T1.Credit+T3.ReconSum
           when DateDiff(Day,t1.refdate,GetDate()) >90 then (T1.Debit-T1.Credit) end '90-Mas',
    CASE T1.TransType
          WHEN '13' THEN (SELECT Y.Comments FROM OINV Y WHERE Y.TransId = T1.TransId)
          WHEN '14' THEN (SELECT Y.Comments FROM ORIN Y WHERE Y.TransId = T1.TransId)
          WHEN '24' THEN (SELECT Y.Comments FROM ORCT Y WHERE Y.TransId = T1.TransId)
          ELSE T1.LineMemo
    END 'Comments'
    FROM OCRD T0
          INNER JOIN JDT1 T1 ON T1.ShortName = T0.CardCode
          INNER JOIN OACT T2 ON T2.AcctCode = T1.Account
          INNER JOIN OJDT T4 ON T4.TransId = T1.TransId
          LEFT JOIN OINV T5 ON T5.TransId = T4.TransId  and t5.ObjType = t4.TransType     
          LEFT JOIN @SAPUNION T3 ON T3.TransId = T1.TransId AND T3.SN = T1.ShortName AND T3.Linea = T1.Line_ID
    WHERE T0.CardType = 'C' /*FOR CLIENTS*/ AND T1.RefDate <= @end AND T2.AcctCode = /*YOUR CLIENT ACCOUNT*/ AND
    (CASE
          WHEN T3.DebHab = 'D' THEN (T1.Debit-T1.Credit-T3.ReconSum)
          WHEN T3.DebHab = 'C' THEN (T1.Debit-T1.Credit+T3.ReconSum)
          ELSE (T1.Debit-T1.Credit)
    END) != '0'
    AND T0.CardCode= @Client
    ORDER BY T0.CardCode,T1.TransId,t1.Ref2
    END
    AND Execute by SAP
    DECLARE @VAR INT, @DATE DATETIME, @BP VARCHAR(8)
    SET @VAR = (SELECT TOP 1 T.DocEntry FROM [dbo].[OINV] T WHERE T.DocDate <='[%0]' AND T.CardCode='[%1]')
    SET @DATE = '[%0]'
    SET @BP = '[%1]'
    EXECUTE [dbo].[Aged_Analysis]
    @end = @DATE,
    @Client = @BP
    Regards
    Floyola
    Edited by: Floyola on Jul 22, 2011 10:17 AM

  • 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).

  • How to calculate the individual sums of multiple columns in a single query

    Hello,
    Using Oracle 11gR2 on windows 7 client. I have a question on calculating sum() on multiple columns on different columns and store the results in a view. Unfortunately I could not post the problem here as it keeps on giving error "Sorry, this content is not allowed", without telling where or what it is! So I had to post it in the stack-overflow forum, here is the link: http://stackoverflow.com/questions/16529721/how-to-calculate-the-individual-sums-of-multiple-columns-in-a-single-query-ora
    Will appreciate any help or suggestion.
    Thanks

    user13667036 wrote:
    Hello,
    Using Oracle 11gR2 on windows 7 client. I have a question on calculating sum() on multiple columns on different columns and store the results in a view. Unfortunately I could not post the problem here as it keeps on giving error "Sorry, this content is not allowed", without telling where or what it is! So I had to post it in the stack-overflow forum, here is the link: http://stackoverflow.com/questions/16529721/how-to-calculate-the-individual-sums-of-multiple-columns-in-a-single-query-ora
    Will appreciate any help or suggestion.
    ThanksLooks like you want a simple group by.
    select
              yr
         ,      mnth
         ,      region
         ,     sum(handled_package)
         ,     sum(expected_missing_package)
         ,     sum(actual_missing_package)
    from test
    group by
         yr, mnth, region
    order by      
         yr, mnth, region;I wouldn't recommend storing your data for year / month in 2 columns like that unless you have a really good reason. I would store it as a date column and add a check constraint to ensure that the date is always the first of the month, then format it out as you wish to the client.
    CREATE TABLE test
         year_month                              date,
        Region                     VARCHAR2(50),
        CITY                       VARCHAR2(50),             
        Handled_Package            NUMBER,       
        Expected_Missing_Package   NUMBER,   
        Actual_Missing_Package     NUMBER
    alter table test add constraint firs_of_month check (year_month = trunc(year_month, 'mm'));
    ME_XE?Insert into TEST (year_month, REGION, CITY, HANDLED_PACKAGE, EXPECTED_MISSING_PACKAGE, ACTUAL_MISSING_PACKAGE)
      2  Values (to_date('2012-nov-12', 'yyyy-mon-dd'), 'Western', 'San Fransisco', 200, 10, 5);
    Insert into TEST (year_month, REGION, CITY, HANDLED_PACKAGE, EXPECTED_MISSING_PACKAGE, ACTUAL_MISSING_PACKAGE)
    ERROR at line 1:
    ORA-02290: check constraint (TUBBY.FIRS_OF_MONTH) violated
    Elapsed: 00:00:00.03
    ME_XE?Insert into TEST (year_month, REGION, CITY, HANDLED_PACKAGE, EXPECTED_MISSING_PACKAGE, ACTUAL_MISSING_PACKAGE)
      2  Values (to_date('2012-nov-01', 'yyyy-mon-dd'), 'Western', 'San Fransisco', 200, 10, 5);
    1 row created.
    Elapsed: 00:00:00.01
    ME_XE?select
      2        to_char(year_month, 'fmYYYY')    as year
      3     ,  to_char(year_month, 'fmMonth')   as month
      4     ,  Region
      5     ,  CITY
      6     ,  Handled_Package
      7     ,  Expected_Missing_Package
      8     ,  Actual_Missing_Package
      9  from test;
    YEAR         MONTH                REGION                         CITY                    HANDLED_PACKAGE EXPECTED_MISSING_PACKAGE ACTUAL_MISSING_PACKAGE
    2012         November             Western                        San Fransisco                       200                       10                      5
    1 row selected.
    Elapsed: 00:00:00.01
    ME_XE?Then you have nice a nice and easy validation that ensures you data integrity.
    Cheers,

  • Tricky SQL query... how to get all data in a single query?

    create table employee_definition (def_id number, def_name varchar(50));
    insert into employee_definition values (100, 'EMAIL');
    insert into employee_definition values (200, 'MOBILE_PHONE');
    insert into employee_definition values (300, 'HOME_PHONE');
    SQL> select * from employee_definition;
        DEF_ID DEF_NAME
           100 EMAIL
           200 MOBILE_PHONE
           300 HOME_PHONE
    create table employee_data (def_id number, def_value varchar(20), emp_id number);
    insert into employee_data values (100, '[email protected]', 123);
    insert into employee_data values (200, '01232222', 123);
    insert into employee_data values (300, '5555', 123);
    insert into employee_data values (100, '[email protected]', 666);
    insert into employee_data values (200, '888', 666);
    insert into employee_data values (300, '999', 666);
    insert into employee_data values (300, '444', 777);
    SQL> select * from employee_data;
        DEF_ID DEF_VALUE                EMP_ID
           100 [email protected]              123
           200 01232222                    123
           300 5555                        123
           100 [email protected]              666
           200 888                         666
           300 999                         666
           300 999                         777
    7 rows selected.I'm supposed to create a SQL that will return me the email, mobile_phone, and home_phone for a set of employees. The result will be something like this:
    EMPLOYEE ID | HOME_PHONE | MOBILE_PHONE | EMAIL
    123         |  5555  |    01232222      | [email protected]
    666         |  999  |    888      | [email protected]
    777         |  444  |    null     | nullThe thing I'm finding difficulty here is that the same column is used to store different values, based on the value in employee_definition table (something like a key/value pair). If I do:
    SQL> select emp_id, def_value as email from employee_data, employee_definition
      2  where employee_data.def_id = employee_definition.def_id
      3  and employee_definition.def_name = 'EMAIL';
        EMP_ID EMAIL
           123 [email protected]
           666 [email protected]'s partially ok.. I'm just getting the definition for 'EMAIL'. But how can I get all the values in a single query, knowing that the column stores different values based on def_name?

    Oh no, not again.
    Entity attribute models always seem like a great idea to people who have been in the profession for five minutes and lack any kind of fundamental knowledge.
    It staggers me that someone with 2,345 posts still believes "you need a 'detail table' for [storing multiple telephone numbers]"
    "A person can have multiple telephone numbers" is not an excuse to build a tired person_attribute table. Niether is the bizarre proposal by someone with over 4k posts who should know better in an earlier post that EAV models are necessary to support temporal fidelity.
    Taken to it's logical conclusion, EAV modelling leads to just two application tables. THINGS and THING_ATTRIBUTES. And when you consider that a THING_ATTRIBUTE is also a THING, why not roll those two tables up into one also? Hmmm, what does THINGS and THING_ATTRIBUTES look like? I know, TABLES and COLUMNS. Who would've guessed? SQL already provides the completely flexible extensible attribute model the advocates of EAV proscribe. But it also has data types, physical data independence, constraints and an efficient query language which EAV does not.
    EAV modelling errodes the semantics of the attributes which are bundled into the "attribute" table.
    There is no point in storing 12 different phone numbers with implied functional dependency to unconstrained and often repeating notional attributes like "MOBILE", "LANDLINE", "WORK", err, "WORK2", err, "MOBILE2", err, ... when this phone type attribute has no semantic value. When you want to call someone, you invariably want to retrive the prefered_phone_number which may depend on a time of day, or a call context.
    These things need to be modelled properly (i.e normalised to BCNF) within the context of the database.

  • How to find Special Characters in a single query

    Dear Experts,
    Your usual help is required to solve the query.My query is "How to find all special characters like (%$*&@,;'/+- etc. in a single query?"
    Thanks.
    e.g.
    A_MIR
    A%SIM
    A*SIM
    A)SIM

    Hi,
    947459 wrote:
    Dear Experts,
    Your usual help is required to solve the query.My query is "How to find all special characters like (%$*&@,;'/+- etc. in a single query?"
    Thanks.
    e.g.
    A_MIR
    A%SIM
    A*SIM
    A)SIMIt's not clear what you want.
    What are "special characters"? Can you list all of them?
    Do you want to find rows where string_column contains any of the special characters? If so
    SELECT     string_column
    FROM     table_x
    WHERE     string_column     != NVL ( TRANSLATE ( string_column
                                        , 'A(%$*&@,;'/+-'
                                , 'A'
                          , 'A'
    ;I assume 'A' is not a special character.
    You could also use regular expressions, but it will be more efficient if you don't use them unless you really need to.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements), and the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}
    You'll get better replies sooner if you always include this information whenever you have a question.

  • How to find the number of hits on a single query

    how to get the information for number of hits on a single query on single day in BI system,
    Regards
    Kumar..

    Following links might help you
    Re: BEx Query is executed how many times???
    Number of times a Query is Run

  • Selecting data from single table with different condition in single query

    Hi everybody...
    I have one table with col1, col2, col3, col4, col5... as columns.
    I want to select col1, col2, col3 with condition (x=y and a=b and c=d)
    I want to select col4, col5 with condition (x=y and a=b and m=n )
    in single query...
    Thanx for ur help

    Given this data set...
    SQL> select * from oddity
      2  /
          COL1       COL2       COL3       COL4       COL5 A X C M
             1          2          3          4          5 B Y   M
             1          2          3          4          5 A Y C N
             1          2          3          4          5 A Y D M
             1          2          3          4          5 A Y D N
             1          2          3          4          5 B Y D N
             1          2          3          4          5 B Y D U
    6 rows selected.
    SQL>The following query meets the requirements. Of course, the requirements as stated are incomplete. I ahave assumed that we select all five columns if C=D andM=N.
    SQL> SELECT decode(c, 'D', col1, '0') AS col1
      2         , decode(c, 'D', col2, '0') AS col2
      3         , decode(c, 'D', col3, '0') AS col3
      4          , decode(m, 'N', col4, '-8') AS col4
      5           , decode(m, 'N', col5, '-8') AS col5
      6  FROM oddity
      7  WHERE a = 'B'
      8  AND  x = 'Y'
      9  /
          COL1       COL2       COL3       COL4       COL5
             0          0          0         -8         -8
             1          2          3          4          5
             1          2          3         -8         -8
    SQL> Cheers, APC

  • How to calculate the area of a large number of polygons in a single query

    Hi forum
    Is it possible to calculate the area of a large number of polygons in a single query using a combination of SDO_AGGR_UNION and SDO_AREA? So far, I have tried doing something similar to this:
    select sdo_geom.sdo_area((
    select sdo_aggr_union (   sdoaggrtype(mg.geoloc, 0.005))
    from mapv_gravsted_00182 mg 
    where mg.dblink = 521 or mg.dblink = 94 or mg.dblink = 38 <many many more....>),
    0.0005) calc_area from dualThe table MAPV_GRAVSTED_00182 contains 2 fields - geoloc (SDO_GEOMETRY) and dblink (Id field) needed for querying specific polygons.
    As far as I can see, I need to first somehow get a single SDO_GEOMETRY object and use this as input for the SDO_AREA function. But I'm not 100% sure, that I'm doing this the right way. This query is very inefficient, and sometimes fails with strange errors like "No more data to read from socket" when executed from SQL Developer. I even tried with the latest JDBC driver from Oracle without much difference.
    Would a better approach be to write some kind of stored procedure, that adds up all the single geometries by adding each call to SDO_AREA on each single geometry object - or what is the best approach?
    Any advice would be appreciated.
    Thanks in advance,
    Jacob

    Hi
    I am now trying to update all my spatial table with SRID's. To do this, I try to drop the spatial index first to recreate it after the update. But for a lot of tables I can't drop the spatial index. Whenever I try to DROP INDEX <spatial index name>, I get this error - anyone know what this means?
    Thanks,
    Jacob
    Error starting at line 2 in command:
    drop index BSSYS.STIER_00182_SX
    Error report:
    SQL Error: ORA-29856: error occurred in the execution of ODCIINDEXDROP routine
    ORA-13249: Error in Spatial index: cannot drop sequence BSSYS.MDRS_1424B$
    ORA-13249: Stmt-Execute Failure: DROP SEQUENCE BSSYS.MDRS_1424B$
    ORA-29400: data cartridge error
    ORA-02289: sequence does not exist
    ORA-06512: at "MDSYS.SDO_INDEX_METHOD_10I", line 27
    29856. 00000 - "error occurred in the execution of ODCIINDEXDROP routine"
    *Cause:    Failed to successfully execute the ODCIIndexDrop routine.
    *Action:   Check to see if the routine has been coded correctly.
    Edit - just found the answer for this in MetaLink note 241003.1. Apparently there is some internal problem when dropping spatial indexes, some objects gets dropped that shouldn't be. Solution is to manually create the sequence it complains it can't drop, then it works... Weird error.

  • Can we show 2 queries in a single query ?

    Hi experts,
    We require an output of a bex query.
    But the output is coming in two different queries.
    Is it possible to show two queries in a single query ?
    Regards,
    Nishuv.

    Hi Praveen,
    We are using bex 3.x. I opened a workbook. in the view toolbar->Toolbars->Control Toolbox.
    I clicked on this. A tool box came in the right side of the sheet.
    The options which we got here are:
    Exit Design mode
    Properties
    View code
    Check box
    Text box
    Command button
    Option button
    List box
    Combo box
    Toogle button spin button
    Scrool bar
    Label
    Image
    More controls
    Tool bar options.
    Here i am not able to see the Analysis grid.
    Is there anything more to be done to get this ?
    Regards,
    Nishuv.

Maybe you are looking for

  • How to create a Email Notification in SRM5.0 ?

    Dear SRM Experts, This is my requirement: Requirement: If Delivery date for a PO is approaching, system should send notification E-mails to approvers and PO initiators. Program execution and dates for notifications will be affiliate specific. Each af

  • Can i use a g3 imac for extra processing power

    hello, can i use an imca g3 graphite to supplement by g5 1.6 model. if so, how? i am using logic and am running into serious processing problems....is there anything i can do to make sure i am using the processing power of the g5 to the max? thaqnks

  • Tax code in MIR5

    While checking the MIR5 Report Tax code isn't coming in it?? Can anybody tell me why it isn't coming?? In MIR4 In can  see the Tax code. But I want to see the Tax code in All my IV Doc.

  • [svn:fx-3.x] 16321: Backport trunk rev 15228 to fix bug SDK-25731 - Clearing validation result  (via 'errorString') prevents new validations.

    Revision: 16321 Revision: 16321 Author:   [email protected] Date:     2010-05-25 15:01:42 -0700 (Tue, 25 May 2010) Log Message: Backport trunk rev 15228 to fix bug SDK-25731 - Clearing validation result (via 'errorString') prevents new validations. I

  • Unable to set status for subscreen

    Dear Experts, In my subscreen, I want to set the fct code for enter. I am not able to set the status so that i can provide the fct code under the standard function keys. In my subscreen I have a list of input screen fields, when i enter the first inp