Logic of aggregation in a SQL query

Oracle Database 11 g Enterprise Edition Release 11.2.0.2.0 - 64 bit Production

I need to write SQL queries to perform the aggregation as mentioned below. Could you please suggest what is the best way to write the query for this task? We have 70 million records in the table of combination and 40 million records in the c_value table.

Combination table
CID PLAN ATTR_1 ATTR_2 ATTR_3 ATTR_4
1001. A C1 P01 S1 #.
1002. A C2 P01 S1 #.
1003 F F1 S1 777 P01
1004 CF C1 P01 S1 777
1005 CF C2 S1 777 P01
2001. A S1 P02 C1 #.
2002. A C2 S1 P02 #.
F 2003 F1 S1 888 P02
2004 CF C1 P02 S1 888
2005 CF C2 S1 888 P02

C_Amount table
CID VALUE
1001 500
1002 400
1003 200
1004 50
1005 100
2001 500
2002 400
2003 400
50 2004
2005 200

The query result
ATTR_2 ATTR_3 value
P01 S1 950
P02 S1 1050

Total amount for P01 = sum (a records plan values) + sum (values of records Plan F)-sum (values of plan SEE plan records where F attr_4 = plan CF attr_4)

= (500 + 400) + (200)-(50 + 100) = 950

Similarly, the amount Total for P02 = (500 + 400) + (400) - (50 + 200) = 1050

create table combination (cid number primary key, plan varchar2 (10), attr_1 varchar2 (10), attr_2 varchar2 (10), attr_3 varchar2 (10), attr_4 varchar2 (10));

create the table c_amount (forced cid number fk_cid combination of references (cid), number of value);
Insert in the combination values (1001, 'A', 'C1', 'P01', "S1", "#");
Insert in the combination values (1002, 'A', 'C2', 'P01', "S1", "#");
Insert in the combination values (1003, 'F', 'F1', 'P01', 'S1', ' 777');
Insert in the combination values (1004, "CF", "C1", "P01", "S1", ' 777');
Insert in the combination values (1005, "CF", "C2", "P01", "S1", ' 777');

insert into c_amount values (1001,500);
insert into c_amount values (1002,400);
insert into c_amount values (1003,200);
insert into c_amount values (1004,50);
insert into c_amount values (1005,100);

Insert in the combination values (2001, 'A', 'C1', 'P02', "S1", "#");
Insert in the combination values (2002, 'A', 'C2', 'P02', "S1", "#");
Insert in the combination values (2003, 'F', 'F1', 'P02', 'S1', ' 888');
Insert in the combination values (2004, "CF", "C1", 'P02', 'S1', ' 888');
insert into values of combination (2005, 'CF', 'C2', 'P02', 'S1', ' 888');

insert into c_amount values (2001,500);
insert into c_amount values (2002,400);
insert into c_amount values (2003,400);
insert into c_amount values (2004,50);
insert into c_amount values (2005,200);
commit;

Hello

user13047999 wrote:

Hi Frank,.

Thanks for your quick response.

Combination.attr_4 play a role in this problem?

Yes. We need to exclude records of plan SEE if attr_4 do correspond with plan F attr_4.

Please run the instructions below insert also.

Insert in the combination values (3001, 'A', 'C3', "P01", "S1", "#");

Insert in the combination values (3002, "CF", "C3", "P01", "S1", ' 111');

insert into c_amount values (3001,300);

insert into c_amount values (3002,300);

commit;

Now the result of the query should be as below

ATTR_2 ATTR_3 value

P01 S1 1250

P02 S1 1050

I think I see; If plan = "CF", the coefficient will be-1 if there is a corresponding 'F' row in the table. otherwise, you want to skip the line "CF".  In other words, "we need to exclude records SEE map if attr_4 is NOT mapped to the F attr_4 plan.

Here's a way to do it:

WITH got_coef AS

(

SELECT attr_2, attr_3, cid

CASE

WHEN the intention ('a', 'F')

THEN 1

WHEN THERE IS)

SELECT 1

COMBINATION cs

WHERE cs.attr_2 = cm.attr_2

AND cs.attr_3 = cm.attr_3

AND cs.attr_4 = cm.attr_4

AND cs.plan = 'F'

)

THEN-1

Coef END AS

COMBINATION cm

WHERE plan IN ('A', 'F', 'CF') - if necessary

)

SELECT gc.attr_2, gc.attr_3

, SUM (ca.value * gc.coef) AS total_value

OF got_coef gc

JOIN c_amount ca ON ca.cid = gc.cid

WHERE gc.coef IS NOT NULL - if necessary

Gc.attr_2 GROUP, gc.attr_3

ORDER BY gc.attr_2, gc.attr_3

;

According to what means "correspondent", you may need to change the EXISTS subquery a bit.

The got_coef of the subquery is not absolutely necessary; you could put the CASE expression in the main query, as I had initially.  (I find it easier to understand in this way, if the argument of the SUM is very complicated, it can be difficult to read and debug.)

Tags: Database

Similar Questions

  • Any difference between the separate function and aggregation in sql query cost?

    Hello
    I've run many models sql stmts - such as:
    one) using a single table
    (b) using the two tables, using simple joins or outer joins

    but I didn't notice a difference in sql stmts in cost and implementation plan...
    In any case, my colleague insists on only using the aggregate function is less expensive compared to
    separate... (something I've not confirmed, that is why I believe that they are exactly the same...)

    For the situation described above under 1 sql... We could for example use
    select distinct deptno
    from emp
    select count(*), deptno
    from emp
    group by deptno
    select distinct owner, object_type from all_objects
    select count(*), owner, object_type from all_objects
    group by owner, object_type
    Have you ever found no difference between the two...?

    Note: I use Ora DB 10g v2.

    Thank you
    SIM

    Alexandre Gelin says:
    function separate and aggregation are for different uses and can give the same result, but if you use the aggregate function to get the separate records, it will be expensive...

    really? I find them almost identical to 11g. Actually GROUP BY is almost always more fast for me in the old days.

    article about this askTom Re: any difference between the separate function and aggregation in sql query cost?
    This applies mainly to the older oracle versions http://www.oracle.com/technology/products/rdb/pdf/distinct_derivedtables_groupby_sort_tech_article.pdf

  • SQL Query - store the result for optimization?

    Good day experts,

    I'm looking for advice on a report. I did a lot of analytical functions to get the basic data that I have to do my report and its takes about 50 min for SQL finish. Now, with these data, I need to create 3 different reports and I can't use the SQL even since there are a lot of aggregation (example would be product group in one case and by customer in 2nd). For each of these different group garages I need another report.

    So how to create 3 reports of 1 SQL query without running the query 3 times?

    First thing that comes to mind is to store the result set in a fictitious table, and then query the table since I get the basic data are about 300 lines and then perform different garages group.

    Best regards

    Igor

    So how to create 3 reports of 1 SQL query without running the query 3 times?

    You already know the obvious answer - store data 'somewhere '.

    If any 'somewhere' depends on your needs and you have not provided ALL the.

    MV - if the query is always the same, you might use a MV and make a complete refresh when you want that new data. The data are permanent and can be queried by other sessions, but the query that accesses the data is frozen in the definition of MV.

    GTT (global temporary table) - If a NEW charge of data AND three reports will be ALWAYS executed by a single session and then data are no longer necessary so a TWG may work. The application that loads the TWG can be different for each race, but the data won't be available for a single session and ONLY for the duration of this session. So if something goes wrong and the session ends the data are missing.

    First thing that comes to mind is to store the result set in a fictitious table, and then query the table since I get the basic data are about 300 lines and then perform different garages group.

    Which is commonly called a "table of REPORT-READY." Those that are useful when data must be permanent and available for multiple sessions/users. Generally, there is a batch (for example the package procedure) that periodically refreshes / updates the data during a window of failure. Or the table can have a column (for example AS_OF) that allows it to contain multiple data sets and the update process let alone the existing data and creates a new set of data.

    If your database is about 300 lines you can consider a table report and even use it to contain multiple data sets. Then, the reports can be written to query the data by using a value AS_OF that wraps and returns the appropriate data. You don't need a window of failure since the oldest data are still available (but can be removed when you no longer need.

    If you need a set of data, you can use a partitioned table work (with only one partition) to collect the new set of data, then a SWAP PARTITION to 'swap' in the new data. Only, this "Exchange" takes a fraction of a second and avoids a window of failure. Once the swap done no matter what user query will get new data.

  • SQL query returns no row vs. multiple lines

    Hello

    I am trying to get the result of a simple sql query,
    If there is no row returned, he would have "No. ROWS" in the result set.
    Other wise all the rows containing data is necessary.

    Let me know how this could be achieved. Under query works for the latter and not first case as mentioned below

    OUTPUT

    + (box 1) when we use B_ID = 123456 +.

    IDS
    -----
    'NO LINE '.

    + (box 2) when we use B_ID = 12345 +.
    IDS
    -----
    1 11112345
    2 22212345
    create table TEMP_AAA
    (
      A_ID VARCHAR2(10),
      B_ID VARCHAR2(10)
    )
    
    INSERT INTO TEMP_AAA(A_ID,B_ID) VALUES('111','12345');
    INSERT INTO TEMP_AAA(A_ID,B_ID) VALUES('222','12345');
    INSERT INTO TEMP_AAA(A_ID,B_ID) VALUES('333','12000');
    INSERT INTO TEMP_AAA(A_ID,B_ID) VALUES('444','10000');
    WITH 
    MATCH_ROWS AS
    (
           SELECT A_ID||B_ID IDS FROM TEMP_AAA WHERE B_ID=12345
    ),
    
    MATCH_ROW_COUNT AS
    (
           SELECT COUNT(1) AS COUNTS FROM MATCH_ROWS
    ),
    
    PROCESSED_ROWS AS
    (
           SELECT
                 CASE WHEN COUNTS = 0
                      THEN 
                       (SELECT NVL((SELECT IDS FROM TEMP_AAA WHERE B_ID=12345),'NO ROWS') IDS FROM DUAL)
                      ELSE
                       MATCH_ROWS.IDS
                 END IDS     
            FROM MATCH_ROWS,MATCH_ROW_COUNT
    )
    
    SELECT * FROM PROCESSED_ROWS;

    Hello

    I think you want to put this on a report or something. I have what would be easier to do this logic there. But if you want that this is possible.
    Like this

    with
    temp_aaa as
    (select '111' a_id ,'12345' b_id from dual union all
    select '222'      ,'12345'  from dual union all
    select '333'      ,'12000'  from dual union all
    select '444'      ,'10000'  from dual
    )
    , wanted_rows as
    ( select  '123456' B_ID from dual)
    select
      temp_aaa.A_ID || temp_aaa.B_ID IDS 
    
    from
      temp_aaa
      ,wanted_rows
    where
      temp_aaa.b_id = wanted_rows.b_id
    union all
    select
      'NO ROWS'
    FROM
      DUAL
    WHERE
      (SELECT COUNT(*) FROM TEMP_AAA, wanted_rows WHERE TEMP_AAA.B_ID = wanted_rows.B_ID) = 0
    

    In addition, you mix var and number of always use the same type or convert explicitly (to_number or to_char)

    WITH
    MATCH_ROWS AS
    (
           SELECT A_ID||B_ID IDS FROM TEMP_AAA WHERE      B_ID           =12345
    --                                                    varchar2(10)   number
    ),
    ...
    

    And again in the

                      THEN
                       (SELECT NVL((SELECT IDS FROM TEMP_AAA WHERE B_ID           =12345),'NO ROWS') IDS FROM DUAL)
    --                                                             varchar2(10)   number
    

    Kind regards

    Peter

  • A necessary sql query

    Hi all

    I have two record values described.

    Select 1 as seq_no, "test1" as double data_set
    Union
    Select 1, '12test' from dual
    Union
    Select 2, 'abcd' from dual
    Union
    Select 2, 'ilm' from dual
    Union
    Select 2, '12test444' from dual

    Here, I need to extract the o/p from the DataSet above below

    1, 12test
    1, test1
    2, 12test444

    Select 1 as seq_no, "test1" as double data_set
    Union
    Select 1, '12test' from dual
    Union
    Select 2, 'abcd' from dual
    Union
    Select 2, 'ilm' from dual

    Here, I need to extract the o/p from the DataSet above below

    1, 12test
    1, test1
    2, abcd
    2, ilm

    The logic behind both above the o/p is

    If the search string 'test' is present in any data set (data set is defined by the same seq_no values), and then print the entire line containing the search string. As in the first data set of record value with seq_val 1 and 2 have two test string 'test', o/p is all the lines contating the search string 'test '.

    If the search string 'test' is not present in any data set (data set is defined by the same values seq_no) then print all lines not containing not the chain sought. As in the second set of data record value with seq_val 2 at once is not test string 'test', o/p is all lines not contating the search string 'test' in the test with 1as and all seq_val data the lines contating the search string 'test' in a set of data with seq_val 2

    Hope I could explain my logic o/p and I need to do in a sql query.

    Waiting for your answers.

    Thanks in advance.

    Hello

    Here's one way:

    WITH     got_rnk          AS
    (
         SELECT     seq_no, data_set
         ,     DENSE_RANK () OVER ( PARTITION BY  seq_no
                                   ORDER BY          CASE
                                       WHEN  INSTR (data_set, 'test') > 0
                                       THEN  1
                                       ELSE  2
                                     END
                           )     AS rnk
         FROM    table_x
    )
    SELECT     seq_no, data_set
    FROM     got_rnk
    WHERE     rnk     = 1
    ;
    

    The CASE expression returns 1 if data_set contains 'test', and it returns 2 if it is not. We will call this number x.
    You are not really interested in x itself. On the contrary, you want all the lines that have the lowest value of x between the lines with the same seq_no. In other words, if a row with a given_seq_num x = 1, then you want all the lines with this seq_no and x = 1, but it the lowest x for a seq_no is 2, then you want the lines with x = 2 instead.
    DENSE_RANK returns the number 1, if the riow data is the more low (or tied for the lowest) in its partition, so if him are all rows with x = 1 in the group, rnk = 1 corresponds to x = 1. But if all lines with the same seq_no have x = 2, then rnk = 1 corresponds to x = 2.

  • Rewrite the sql query

    Hello

    I need to rewrite this SQL query to give the same result, but a way more resorcefull.
    Probably using aggregation, but I'm not sure.
    Can someone give me a head start.
    desc resource_bundles
    
    Name          Null     Type                
    ------------- -------- ------------------- 
    LOCALE        NOT NULL CHAR(5)             
    BUNDLE_NAME   NOT NULL VARCHAR2(32)        
    RESOURCE_NAME NOT NULL VARCHAR2(64)        
    VALUE_STRING           VARCHAR2(2048 CHAR) 
    
    select a.bundle_name,a.resource_name, a.value_string as Czech,(select b.value_string 
                                             from resource_bundles b 
                                             where b.bundle_name = a.bundle_name
                                             and b.resource_name = a.resource_name
                                             and b.locale = 'en_US'
                                            )as English,
                                             (select c.value_string 
                                             from resource_bundles c 
                                             where c.bundle_name = a.bundle_name
                                             and c.resource_name = a.resource_name
                                             and c.locale = 'ru_RU'
                                             ) as Russian,
                                             (select d.value_string 
                                             from resource_bundles d 
                                             where d.bundle_name = a.bundle_name
                                             and d.resource_name = a.resource_name
                                             and d.locale = 'it_IT'
                                            ) as Italian
    from resource_bundles a
    where a.locale = 'cs_CZ';
    Thank you

    Published by: BluShadow on April 15, 2011 12:20
    addition of {noformat}
    {noformat} tags                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

    Hello

    Here's one way:

    SELECT       bundle_name, resource_name
    ,       MIN (CASE WHEN locale = 'cs_CZ' THEN value_string END)     AS czech
    ,       MIN (CASE WHEN locale = 'en_US' THEN value_string END)     AS english
    ,       MIN (CASE WHEN locale = 'ru_RU' THEN value_string END)     AS russian
    ,       MIN (CASE WHEN locale = 'it_IT' THEN value_string END)     AS italian
    FROM       resouce_bundles
    GROUP BY  bundle_name, resource_name
    HAVING       COUNT (CASE WHEN locale = 'cs_CZ' THEN 1 END)     > 0
    

    If you would care to view the information that Centinul mentioned, then I could test it.

    Published by: Frank Kulash, April 17, 2011 15:08
    Removed extra "(" in 'HAVING COUNT ((...)'.

  • The search syntax of SQL query against the data type varchar2 preserving valid data.

    Have a data model that we are not allowed to change and the column in question is a varchar2 (20). The column has at this stage no foreign key to the list of valid values. So, until we can get those who control the data model in order to make the adjustments we need for a SQL query that root out us bad data on the hours fixed.

    Is what we expect to be good data below:

    -Whole number, without floating point
    -Length of 5 or less (greater than zero but less than 99999)
    -Text "No_RP" can exist.

    Request demo below works most of the time with the exception of 'or Column1 is null' is not contagious in the null record. I tried to change the logical terms around, but did not understand the correct layout still provide it. So help would be greatly appreciated it someone could put me straight on how to properly register a null value in the recordset that has been selected with other types of error for end users to correct their mistakes. Another thing, I suppose there could be a better approach syntactically to a call find all offender characters such as *, &, (and so on.)

    WITH Sample_Data AS (SELECT '0' collar OF DOUBLE UNION ALL)
    SELECT "2" collar OF DOUBLE UNION ALL
    SELECT "99999" col OF DOUBLE UNION ALL
    SELECT "100000" col OF DOUBLE UNION ALL
    SELECT '1 a' collar OF DOUBLE UNION ALL
    SELECT the "ABCD" OF DOUBLE UNION ALL pass
    SELECT 'A1' collar OF DOUBLE UNION ALL
    SELECT ' *' collar OF DOUBLE UNION ALL
    SELECT "/" pass OF DOUBLE UNION ALL
    SELECT '-' col OF DOUBLE UNION ALL
    SELECT ' ' collar OF DOUBLE UNION ALL
    SELECT "pass OF DOUBLE UNION ALL
    4. SELECT 5 6' collar OF DOUBLE UNION ALL
    SELECT "24.5" collar OF DOUBLE UNION ALL
    SELECT '-3' collar OF DOUBLE UNION ALL.
    SELECT 'A' collar OF DOUBLE UNION ALL
    SELECT 'F' OF DOUBLE UNION ALL cervical
    SELECT the 'Z' OF DOUBLE UNION ALL pass
    SELECT the pass 'Bye' FROM DUAL UNION ALL
    SELECT the "Hello World" OF DOUBLE UNION ALL pass
    SELECT "=" col OF DOUBLE UNION ALL
    SELECT "+" col OF DOUBLE UNION ALL
    SELECT '_' pass OF DOUBLE UNION ALL
    SELECT '-' col OF DOUBLE UNION ALL
    SELECT ' (' col OF DOUBLE UNION ALL)
    SELECT ')' collar OF DOUBLE UNION ALL
    SELECT '&' collar OF DOUBLE UNION ALL
    SELECT ' ^' collar OF DOUBLE UNION ALL
    SELECT '%' collar OF DOUBLE UNION ALL
    SELECT the pass of "$" OF DOUBLE UNION ALL
    SELECT the pass ' # ' TO DOUBLE UNION ALL
    SELECT ' @' collar OF DOUBLE UNION ALL
    SELECT '!' collar OF DOUBLE UNION ALL
    SELECT ' ~' collar OF DOUBLE UNION ALL
    SELECT "' collar OF DOUBLE UNION ALL
    SELECT '.' pass FROM DUAL
    )
    SELECT col from Sample_data
    WHERE (translate (col, '_0123456789', '_') is not null
    or length (col) > 5
    col = 0 or
    or col is null)
    and (upper (col) <>'NO_RP');

    One more thing, I also took the approach of the regular expression, but he could not understand. If anyone knows how to do with this approach, I would also appreciate learning this method as well. Below is a close because I had. Impossible to get a range to work as "between 0 and 100000", guessing because of the comparison of varchar2 and # even attempted using to_char and to_number.

    Select to_number (column1) from the testsql where REGEXP_LIKE (column1, ' ^ [[: digit:]] + $') ORDER BY to_number (column1) CSA;

    Thanks in advance for anyone to help.

    Nick

    Hello

    Thanks for posting the sample data in a useable form.
    It would be useful that you also posted the accurate results you wanted from this data. You want the same results as those produced by the query you posted, except that nulls should be included? If so:

    SELECT     col
    FROM     sample_data
    WHERE     CASE
             WHEN  UPPER (col) = 'NO_RP'               THEN  1
             WHEN  col IS NULL                    THEN -1
             WHEN  LTRIM (col, '0123456789') IS NOT NULL     THEN -2
             WHEN  LENGTH (col) > 5               THEN -3
                                           ELSE TO_NUMBER (col)
         END     NOT BETWEEN     1
                  AND          99999
    ;
    

    The requirement that pass! = 0 gives that much more difficult. You could test easily for an integer from 1 to 5 digits, but then you must have a separate condition to make sure that the chain was not '0', '00', '000', ' 0000 'or ' 00000'.
    (Unlike Solomon, I guess that do not want to choose no-0 numbers starting by 0, such as ' 007 'or ' 02138'.)

    Using regular expressions, you may lose a few keystrokes, but you also lose a lot of clarity:

    SELECT     col
    FROM     sample_data
    WHERE     REGEXP_LIKE ( col
                  , '^0{1,5}$'
                  )
    OR NOT     REGEXP_LIKE ( NVL ( UPPER (col)
                     , 'BAD'
                     )
                  , '^(([1-9][0-9]{0,4})|NO_RP)$'
                  )
    ;
    

    Published by: Frank Kulash, December 13, 2010 21:50

    Published by: Frank Kulash, December 13, 2010 22:11
    Added regular expression solution

  • Please help me with this SQL query

    I'm practicing of SQL queries and met one involving the extraction of data from 3 different tables.

    The three paintings are as below

    < pre >
    Country
    Location_id country
    LOC1 Spain
    loc2 England
    LOC3 Spain
    loc4 USA
    loc5 Italy
    loc6 USA
    loc7 USA
    < / pre >
    < pre >


    User
    user_id location_id
    loc1 U1
    loc1 U2
    loc2 U3
    loc2 U4
    loc1 U5
    U6 loc3
    < / pre >
    < pre >


    Publish
    user_id post_id
    P1 u1
    P2 u1
    U2 P3
    P4 u3
    P5 u1
    P6 u2
    < / pre >

    I am trying to write a SQL query - for each country of the users, showing the average number of positions

    I understand the logic behind all this that we must first consolidate all locations, and then the users in one country and then find the way to their positions.
    But, I'm having a difficulty to this format SQL. Could someone help me please with this request.

    Thank you.

    Select
    Country.Country,
    Count (*) Totalpostspercountry,
    Count (distinct post.user_id) Totaldistincuserspercountry,
    count (*) / count (distinct post.user_id) Avgpostsperuserbycountry
    Of
    countries, have, post
    where country.location_id = muser.location_id
    and muser.user_id = post.user_id
    Country.country group

    The output is like this for your sample data - hope that's what you're looking for :)

    COUNTRY, TOTALPOSTSPERCOUNTRY, TOTALDISTINCUSERSPERCOUNTRY, AVGPOSTSPERUSERBYCOUNTRY
    In England, 1, 1, 1.
    Spain, 5, 2, 2.5.

  • Components catalog SQL query and caching

    Hello

    It seems that SQL query result sets components catalog caching and go to the DB only after restarting the engine. Is it possible to disable this caching and force SQL queries to run each time?

    Thank you.
    Nick.

    Hi Nick,

    Take a look at the log file of your engine. To execute SQL queries when running logic. See if you get any 'error', 'Serious' or 'Warning' engine log messages when you run your query.

    Hope this helps,
    Dan

  • A difficult dynamic SQL query problem

    Hi all

    I have a very interesting problem to work:

    We have this special table defined as follows:

    CREATE TABLE sales_data)
    sales_id NUMBER,
    NUMBER of sales_m01
    NUMBER of sales_m02
    NUMBER of sales_m03
    NUMBER of sales_m04
    NUMBER of sales_m05
    NUMBER of sales_m06
    NUMBER of sales_m07
    NUMBER of sales_m08
    NUMBER of sales_m09
    NUMBER of sales_m10
    NUMBER of sales_m11
    NUMBER of sales_m12
    sales_prior_yr NUMBER);
    /

    Columns ' sales_m01... sales_m12' represents aggregated monthly sales, what "sales_m01" is translated by "sales for the month of January, January is the first month,"sales_m02"in sales for the month of February and so on.»

    The problem I encounter is that we have a project that requires that a parameter is passed to a stored procedure that represents the number of months which is then used to create a SQL query with aggregations of next mandatory field, which depends on the parameter passed:

    Example 1: entry of parameter: 4
    Should be built dynamically to SQL query:

    SELECT
    Sum (sales_m04) as CURRENT_SALES,
    Sum (sales_m01 + sales_m02 + sales_m03 + sales_m04) SALES_YTD
    Of
    sales_data
    WHERE
    sales_id = '0599768';

    Example 2: input parameter: 8
    Should be built dynamically to SQL query:

    SELECT
    Sum (sales_m08) as CURRENT_SALES,
    SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04 +)
    sales_m05 + sales_m06 + sales_m07 + sales_m08) SALES_YTD
    Of
    sales_data
    WHERE
    sales_id = '0599768';


    So in a sense, the contents of SUM(sales_m01...n) would vary according to the parameter, which must be a number between 1... 12 what is a month, which in turn corresponds to a range of real field on the table itself. The resulting dynamic query should include only those columns/fields in the table that is within the range given by the input parameter and does not account for all the other columns/fields.

    Any solution is greatly appreciated.

    Thank you.
    SQL> declare
      cols long;
      param integer := 6;
      sales_id integer := 0599768;
    begin
      for i in 1..param loop
        cols := cols || 'sales_m' || to_char(i, 'fm00') || '+';
      end loop;
    
      dbms_output.put_line('select sum(sales_m'||to_char(param,'fm00')||') current_sales, sum(' || rtrim(cols,'+') || ') sales_ytd from sales_data WHERE sales_id = :1');
    end;
    /
    select sum(sales_m06) current_sales, sum(sales_m01+sales_m02+sales_m03+sales_m04+sales_m05+sales_m06) sales_ytd from sales_data WHERE sales_id = :1
    PL/SQL procedure successfully completed.
    

    Now it should be obvious:
    Instead of dbms_output OPEN a refcursor:

    SQL> declare
      cols long;
      param integer := 6;
      sales_id integer := 0599768;
      cur sys_refcursor;
    begin
      for i in 1..param loop
        cols := cols || 'sales_m' || to_char(i, 'fm00') || ',';
      end loop;
    
      open cur for 'select sum(sales_m'||to_char(param,'fm00')||') current_sales, sum(' || rtrim(cols,',') || ') sales_ytd from sales_data WHERE sales_id = :1' using sales_id;
      .....
    end;
    /
    

    Published by: michaels2 on July 26, 2009 09:49

    replaced ',' with ' + '.

  • SQL query SUM and AVG

    Hi all

    I think I'm really stupid but I have problems of SQL query.

    I have a table with many lines of operations which all refer to different stores, for example:

    Store... _Sales_... _Month_
    Reading... 200 k... April
    Leeds... 50k................ April
    Manchester... 70k................ May
    Reading... 100 k... May

    I need to arrive at the average sales for the month combined as a total. That is the average income of store for a given period is 200 k + 50 k + 70 k + 100 k / * 3 * (because there are only 3 unique shops) - I hope this makes sense!

    So, basically, I'm doing both a query of the SUM (and company store) and then out of the average of all the stores together. Is this possible?


    Thank you

    Hello

    This query returns 140 which seems to be the correct value:

    with data as
    ( select 'Reading' Store
      , 200 sales
      from dual
      union
      select 'Leeds'
      , 50
      from dual
      union
      select 'Manchester'
      , 70
      from dual
      union
      select 'Reading'
      , 100
      from dual
    )
    select sum(sales)
    , count( distinct store )
    , sum(sales)/count(distinct store)
    from data
    

    There are several options:
    1. you can get two IR on one page (using IFRAMEs - search for that word on the Forum)...
    2. you create another region with the above query and that position just below the report
    3. in the foot of the region call a process of PL/SQL (using AJAX) that calculates the value using the query and print it (via htp.p)

    Greetings,
    Roel

    http://roelhartman.blogspot.com/
    http://www.bloggingaboutoracle.org/
    http://www.Logica.com/

    You can assign this answer to your question in marking it as useful or Correct ;-)

  • Œuvres SQL query to MS SQL Server 2008, but not when you use the database kit

    I have this SQL query:

    DECLARE TABLE (@DataTypeTable)
    Name varchar (128).
    TypeID INT)

    -Add comma delimeted type data in the temporary table names
    INSERT INTO @DataTypeTable (name)
    SELECT * from WhatWeShouldDoRead.func_Split (@DataTypeTrimmed, ',')

    SELECT the name OF @DataTypeTable

    That takes a comma delimited by the string and returns the string as a table.  It works correctly in Microsoft SQL Server Management Studio.  When I run this as a stored procedure I return nothing.  There are no errors, SQL or otherwise.  I checked that I am connected to the correct database and the stored procedure is responsible without changing any error chain which is reported of this stored procedure (that code is not shown in the example above).  Has anyone seen this problem before, or have experience with SQL/Labview interfaces to tell me what I am doing wrong?

    Thanks in advance.


  • LabVIEW sql query

    HI HI... I'm a student doing a project related to labview. My task is to create a vi, type a user name and password to continue the whole VI.

    As I am a newbie to SQL query language, can anyone help me this?... This isn't like the VI with password lock

    There is a connection of the user called button in my main façade... u by clicking on it, a pop-up window will come out asking you a user name and a password. If the user name and the password is correct, then you can proceed. The problem is that I'm stuck with database...
    Help me pls!

    with respect,

    Ray

    Hello

    You have two cases:

    (1) connect to the database with string (link a string of connection information), and then type something like this:
    Driver is SQL Native Client;. Server = IP. Add.re.SS; UID = username; PW = *** ; Database = MyDatabase (depends on your database)

    (2) use a UDL file (you can configure it to connect to your database, with specific format). Remember that the connection is successful with test button.

    There is a UDL file that you can edit here: C:\Program NIUninstaller Instruments\LabVIEW 2010\examples\database\Labview.udl

    Edit: The connection dropped, you can set the path to an mdb file, and I think you can give the path of your accdb file.

    Kind regards

  • SQL query for empty string

    I am trying to execute the following SQl query, SELECT * failure WHERE ID = '123 ' AND RepairAction =' '; using the DB tools run Query.vi. This query never find record in my database. My database contains a record where the registered ID contains the value '123' and the RepairAction field is an empty string. If I remove the declaration 'AND RepairAction' ';' my query text, the record is found. I think my problem is that I do not use the correct syntax to describe and an empty string. I tried the following: "," ",""," "and NULL as empty and none of these work string arguments.

    I was hoping someone might be able to tell me what the correct syntax is an empty string or if there is another approach that I take.

    Thanks in advance for your help,

    Jim

    Jim,

    Just to be sure, have you used 'is' instead of '=' in this command?

    This makes all the difference in this command.

    Cerati

  • Support of SQL query: what tasks are Sunday from 07:00 - 12:00

    Hello tide Admins.

    I need to do a SQL query that can give me a list of jobs that are running on a given (Sunday) day from 07:00 - 12:00.  Our environment is not a maintenance window.  Therefore, whenever there is application of patches or upgrades, it causes more work and risk of failure of the tide tasks.    By moving jobs over the period from 07:00 - 12:00 Sunday, patch can be completed without disrupting the calendar.

    Im not the best at the SQL script and can not get my script to work. any help would be great. Here's what I have so far.  I get the error ' could not find identifier multi-player jobmst.jobmst_name.  IM using Tidal 6.0.3 with SQL for DB Admeral table.

    SELECT dbo.jobdtl.jobdtl_id, dbo.jobmst.jobmst_prntname, dbo.jobmst.jobmst_name

    FROM dbo.jobdtl INNER JOIN

    dbo.jobmst ON dbo.jobdtl.jobdtl_id = dbo.jobmst.jobdtl_id

    WHERE (dbo.jobdtl.jobdtl_fromdt > 14 September 2016 06:00 ') AND (dbo.jobdtl.jobdtl_fromdt< '09/11/2016="" 012:00:00="">

    GROUP OF dbo.jobdtl.jobdtl_id, dbo.jobmst.jobmst_prntname, dbo.jobmst.jobmst_name

    Hi Jeff

    The time window from the jobdtl returns only jobs that have an early start time and windows of time from beginning to the end, so there may be some tasks which are not time bound but have dependencies on other jobs, variables, etc.

    Here are the 2 SQL queries against the table jobrun and jobmst:

    -The list of jobs that took place last Sunday between 07:00 and 12:00

    SELECT jobmst.jobmst_prntname, jobmst.jobmst_name, jobrun.jobrun_time FROM jobrun
    JOIN jobmst on jobrun.jobmst_id = jobmst.jobmst_id
    WHERE jobrun.jobrun_time > = 9/11/2016 07:00 ' and jobrun.jobrun_time<= '9/11/2016="" 12:00="">
    ORDER BY jobrun.jobrun_time

    -For a list of jobs that are scheduled to run on Sunday to come between 07:00 and 12:00

    SELECT jobmst.jobmst_prntname, jobmst.jobmst_name, jobrun.jobrun_esttime FROM jobrun
    JOIN jobmst on jobrun.jobmst_id = jobmst.jobmst_id
    WHERE jobrun.jobrun_esttime > = 9/18/2016 07:00 ' and jobrun.jobrun_esttime<= '9/18/2016="" 12:00="">
    ORDER BY jobrun.jobrun_esttime

    ARO

    The Derrick

Maybe you are looking for

  • M30 DVD-UDF & DVD + R writing

    Hi people,I wonder if anyone has figured this out already... So I try to use the format UDF DVD + RW on my M30, using Nero InCD. Initially, InCD would not install and tell me that there is a conflict with the DVD-RAM drivers.After installing these dr

  • Logic stops in the middle of recording

    Hello I never had no problem with recording in logic, but in the last week or so he continues to stop in the middle of recording. I could do something very simply, as posing a piano in a blank project, and after a few logical agreements stops himself

  • Laptop overheats quickly / how to fix this?

    Hi all Laptop Pavilion dv6 - 7013cl, I bought six months ago and it warms quickly if I open more then two ore 3 programs. Please could you help me. It will be very useful Serial number [edited by Moderator] product number B5S13UA warranty status warr

  • power adapter 608425-002

    During a trip overseas (220 volts) can I use my power adapter 608425-002 normally with my HP G72 laptop as I have the right plug adapter?

  • bloqueadores of pop-up windows

    ALGUEM PODE ME HELP FAVOR? PROCURO UM BLOQUEADOR POPUPS WHAT BLOQUEIA PROPAGANDA SITES QUANDO EU ASSISTO TV ONLINE VIA INTERNET. OBRIGADO ALGUEM SE PUDER ME ORIENTAR!