Help creating sql statement

I need help in creating a sql statement. For example lets say i have 3 tables one(key_id, os), two(key_id, type, desc), three(type, desc). I need to create a statement that is kind of like this but i need all rows in table one returned also.
select a.key_id, b.key_id, c.desc
from one a, two b, three c
where a.key_id = b.key_id and b.type = c.type;
Message was edited by:
user457357

Or
michaels>  with one as
(select 10 key_id from dual union all
  select 20 from dual union all
  select 30 from dual union all
  select 40 from dual union all
  select 50 from dual),
two as
(select 10 key_id,'aa' type from dual union all
  select 20, 'aa' from dual union all
  select 30, 'bb' from dual),
three as
(select 'aa' type ,'Artificial' des from dual union all
  select 'bb','Bulk' from dual)
select a.*, b.key_id, c.des
  from one a, two b, three c
where a.key_id = b.key_id(+)
    and b.type = c.type(+)
    KEY_ID   KEY_ID_1 DES      
        10         10 Artificial
        20         20 Artificial
        30         30 Bulk     
        40                     
        50                     

Similar Messages

  • Need help for sql statement

    Hi,
    Need help to write sql statement.
    create table t_dt ( dt_start date, dt_end date, amount number);
    insert into t_dt values('1-Jan-10','10-Feb-10',12);
    insert into t_dt values('11-Feb-10','10-Mar-10',10);
    insert into t_dt values('11-Mar-10','20-Apr-10',8);
    insert into t_dt values('21-Apr-10','28-Jun-10',10);
    insert into t_dt values('29-Jun-10','20-Sep-10',10);
    insert into t_dt values('21-Sep-10','10-Oct-10',10);
    insert into t_dt values('11-Oct-10','31-Dec-10',8);
    insert into t_dt values('1-Jan-11','10-Feb-11',8);
    insert into t_dt values('11-Feb-11','10-Mar-11',7);
    insert into t_dt values('11-Mar-11','20-Apr-11',6);
    insert into t_dt values('21-Apr-11','28-Jun-11',6);
    insert into t_dt values('29-Jun-11','20-Sep-11',6);
    insert into t_dt values('21-Sep-11','10-Oct-11',4);
    insert into t_dt values('11-Oct-11','31-Dec-11',8);
    Result should be like below..
    dt_start     dt_end     Amount
    1-Jan-10     10-Feb-10     12
    11-Feb-10     10-Mar-10     10
    11-Mar-10     20-Apr-10     8
    21-Apr-10     10-Oct-10     10
    11-Oct-10     10-Feb-11     8
    11-Feb-11     10-Mar-11     7
    11-Mar-11     20-Sep-11     6
    21-Sep-11     10-Oct-11     4
    11-Oct-11     31-Dec-11     8
    Just to explain the example, take a row with start date as 21-Apr-10 in the above insert statements, since it has the same amount for next two rows (i.e. with start date '29-Jun-10' and '21-Sep-10') these 3 rows should be converted to represent only 1 row in the result and the start date and end date should be changed per the result shown above.
    Thanks.

    Hello
    I think this gives yuo what you need....
    SELECT
        MIN(dt_start),
        MAX(dt_end),
        amount
    FROM
        (   SELECT
                dt_start,
                dt_end,
                MAX(marker) OVER(ORDER BY dt_start) marker,
                amount
            FROM
                    Select
                        dt_start,
                        dt_end,
                        amount,
                        CASE
                            WHEN LAG(amount) OVER(ORDER BY dt_start) <> amount THEN
                                ROW_NUMBER() OVER(ORDER BY dt_start)
                        END marker
                    from t_dt
    GROUP BY
         amount,
         marker
    order by     
         MIN(dt_start)
    MIN(DT_START)        MAX(DT_END)              AMOUNT
    01-JAN-2010 00:00:00 10-FEB-2010 00:00:00         12
    11-FEB-2010 00:00:00 10-MAR-2010 00:00:00         10
    11-MAR-2010 00:00:00 20-APR-2010 00:00:00          8
    21-APR-2010 00:00:00 10-OCT-2010 00:00:00         10
    11-OCT-2010 00:00:00 10-FEB-2011 00:00:00          8
    11-FEB-2011 00:00:00 10-MAR-2011 00:00:00          7
    11-MAR-2011 00:00:00 20-SEP-2011 00:00:00          6
    21-SEP-2011 00:00:00 10-OCT-2011 00:00:00          4
    11-OCT-2011 00:00:00 31-DEC-2011 00:00:00          8
    9 rows selected.HTH
    David
    Edited by: Bravid on Feb 23, 2012 12:08 PM
    Beaten to it by Frank! :-)

  • Help with SQL statement in a coldfusion application

    I created 2 drop down list boxes one that contains the months
    and the second that contains the year. Right now my sql statement
    is Select * from job where releaseDate=#imageDate#. Now this was
    written in 2006 and I didn't know they were going to continue to
    use the tool in 2007. So now I need a sql statement that if a user
    selects Jan 2007 that all of jan 2007 will display. The format for
    the datetime field in the database is Jan 2 2007 hh:mm:ss the first
    box is named imageDate and the second is called StatusDate

    Take a look at the T-SQL datepart function.
    Bryan Ashcraft (remove BRAIN to reply)
    Web Application Developer
    Wright Medical Technology, Inc.
    Macromedia Certified Dreamweaver Developer
    Adobe Community Expert (DW) ::
    http://www.adobe.com/communities/experts/
    "rere" <[email protected]> wrote in message
    news:fjp4im$fqk$[email protected]..
    >I created 2 drop down list boxes one that contains the
    months and the
    >second
    > that contains the year. Right now my sql statement is
    Select * from job
    > where
    > releaseDate=#imageDate#. Now this was written in 2006
    and I didn't know
    > they
    > were going to continue to use the tool in 2007. So now I
    need a sql
    > statement
    > that if a user selects Jan 2007 that all of jan 2007
    will display. The
    > format
    > for the datetime field in the database is Jan 2 2007
    hh:mm:ss the first
    > box is
    > named imageDate and the second is called StatusDate
    >

  • How to dynamically create sql statement for Defaulting Segment Values?

    Hi,
    Navigation:
    1) Descriptive/Segments
    2) Query for DFF to be modified
    3) Uncheck “Freeze Flexfield Definition”
    4) (B) Segments
    5) Segments Summary form opens
    6) (B) open - Segments form opens
    Now, here I want to specify Default type as "SQL Statement" and in the default value field I want to use SQL statement with parameters (to evaluate the default value).
    The parameters should be pass at runtime from the form in which we have this DFF. The parameters value should be one of the values which get evaluated at runtime in the form window.
    Please suggest how we can achieve this?
    Or is there any alternative to achieve this?
    Thanks!!
    Regards,
    Narender
    Edited by: Narender Singh on Mar 30, 2010 7:47 AM
    Edited by: Narender Singh on Mar 30, 2010 7:48 AM

    Jason,
    it is possible, though not so simple as with a report.
    What you need to do is to create a pipelined function, that returns your date and count data. This pipelined function can be the base of a pseudo-table, which can be used in a select. For the pipelined function you need to define types for one row and a table to define the return-type for your function:
    create or replace type calendar_row as object (date_time date, description varchar2(250));
    create type calendar_table as table of calendar_row;
    Then you can create the package with the function:
    ================================================
    create or replace package dyn_calendar is
    procedure set_query(i_query in varchar2);
    function view_source return calendar_table pipelined;
    end;
    create or replace package body dyn_calendar is
    v_query varchar2(100) := null;
    procedure set_query(i_query in varchar2) is
    begin
    v_query := i_query;
    end;
    function view_source return calendar_table pipelined is
    TYPE cursor IS REF CURSOR;
    c_cal cursor;
    v_date_time date := null;
    v_description varchar2(100) := null;
    r_cal calendar_row;
    begin
    open c_cal for v_query;
    fetch c_cal into v_date_time, v_description;
    loop
    exit when c_cal%notfound;
    r_cal := calendar_row(v_date_time, v_description);
    pipe row(r_cal);
    fetch c_cal into v_date_time, v_description;
    end loop;
    return;
    end;
    end;
    ================================================
    Now you can set query in a PL/SL region before the calendar:
    dyn_calendar.set_query(SELECT count(*), ' || :P8_SOURCE_DATE || ' FROM ' || :P8_SOURCE_TABLE || ' GROUP BY ' || :P8_SOURCE_DATE);
    and you can base your calendar on the query:
    select * from table(dyn_calendar(view_source))
    Good luck,
    Dik

  • Help with sql statements and Java

    Hi,
    How can I create a string kind of like this
    Select * From Students Where Name Like "Bob Burns";
    As the sql statement might indicate I am using MS Access. I seem to be having problems with the double quotes required by the Like operator in MS Access, Java views that as a beginning of a string as oppposed to an actual string value.

    Like this:
        Connection connection = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try  {
            connection = ...get from connection pool...;
            String sql = "select ... from ... where name like ?";
            stmt = connection.prepareStatement(sql);
            stmt.setObject(1, "%Bob%", java.sql.Types.VARCHAR);
            res = stmt.executeQuery();
            while (res.next()) { ...the usual...; }
        } finally {
            ...close res, stmt & return connection to pool...
        }You can try stmt.setString() instead of setObject() but rumor has it that some mssql drivers have a bug that makes setString() not work with "like", but oddly enough setObject() works.

  • Need Help On SQL Statement

    I am using Sybase as my back end database. I need help on my SQL statement regarding datetime. The datetime is store as a 9 digit integer in the database (...I believe it is a Decimal(30,6) format, let me know if I am wrong).
    If I do this, "select * from mytable;" It works out fine (except I don't know what the date means e.g. 998919534)
    If I do this, "select * from mytable where datetime_col < '9/5/2002' ; I got an error. I even tried '9/5/02 11:00 000 am' but it didn't help.
    How do I specify a date or datetime in my query?
    Thanks in advance.

    I execute the sql statement
    select * from mytable where datetim_col < convert(datetime, '3/4/2002', 101) ;
    I got mix result. I got an error message "cannot convert 10375584 to a date.
    Yet, he statistics window of the I-sql says
    "estimated 493 rows in query (I/O estimate 87)
    PLan> mytable (seq)"
    It looks like I my the SQL statement is correct and then the system can't display it in the Data window.
    Any thought ?

  • Need help on SQL Statement for UDF

    Hi,
    as I am not so familiar with SQL statements on currently selected values, I urgently need help.
    The scenario looks as follows:
    I have defined two UDFs named Subgroup1 and Subgroup2 which represent the subgroups dependent on my article groups. So for example: When the user selects article group "pianos", he only sees the specific subgroups like "new pianos" and "used pianos" in field "Subgroup1". After he has selected one of these specific values, he sees only the specific sub-subgroups in field "Subgroup2", like "used grand pianos".
    I have defined UDTs for both UDFs. The UDT for field "Subgroup1" has a UDF called "ArticleGroup" which represents the relation to the article group codes. The UDT for field "Subgroup2" has a UDF called "Subgroup1" which represents the relation to the subgroups one level higher.
    The SQL statement for the formatted search in field "Subgroup1" looks as follows:
    SELECT T0.[Name] FROM [dbo].[@B_SUBGROUP1]  T0 WHERE T0.[U_ArticleGroup]  = (SELECT $[OITM.ItmsGrpCod])
    It works fine.
    However, I cannot find the right statement for the formatted search in field "Subgroup2".
    Unfortunately this does NOT WORK:
    SELECT T0.[Name] FROM [dbo].[@B_SUBGROUP2]  T0 WHERE T0.[U_Subgroup1]  = (SELECT $[OITM.U_Subgroup1])
    I tried a lot of others that didn't work either.
    Then I tried the following one:
    SELECT T0.[Name] FROM [dbo].[@B_SUBGROUP2]  T0 WHERE T0.[U_Subgroup1] = (SELECT T1.[Code] FROM [dbo].[@B_SUBGROUP1] T1 WHERE T1.[U_ArticleGroup] = (SELECT $[OITM.ItmsGrpCod]))
    Unfortunately that only works as long as there is only one specific subgroup1 for the selected article group.
    I would be sooooo happy if there is anyone who can tell me the correct statement for my second UDF!
    Thanks so much in advance!!!!
    Edited by: Corinna Hochheim on Jan 18, 2010 10:16 PM
    Please ignore the "http://" in the above statements - it is certainly not part of my SQL.
    Please also ignore the strikes.

    Hello Dear,
    Use the below queries to get the values:
    Item Sub Group on the basis of Item Group
    SELECT T0.[Name] FROM [dbo].[@SUBGROUP]  T0 WHERE T0.[U_GroupCod] =$[OITM.ItmsGrpCod]
    Item Sub Group 1 on the basis of item sub group
    SELECT T0.[Name] FROM [dbo].[@SUBGROUP1]  T0 WHERE T0.[U_SubGrpCod]=(SELECT T0.[Code] FROM [dbo].[@SUBGROUP]  T0 WHERE T0.[Name] =$[OITM.U_ItmsSubgrp])
    Sub group 2 on the basis of sub group 1
    SELECT T0.[Name] FROM [dbo].[@SUBGROUP2]  T0 WHERE T0.[U_SubGrpCod1]=(SELECT T0.[Code] FROM [dbo].[@SUBGROUP1]  T0 WHERE T0.[Name] =$[OITM.U_ItmsSubgrp1])
    this will help you.
    regards,
    Neetu

  • Help in SQL statement!!

    How to pass in the strings with commas in the SQL statement. I have a SQL statement which looks like this:
    String query = "SELECT Product FROM Product where Risk LIKE "+ risk +" and Priority="+ priority +"";
    And the 2 values that I'm going to pass in is "R1,R2" and "P1,P2"; When I run it, there is an error. May I know how to improve my SQL statement so that it can accept the two values. Thanx
                   

    I would have used keyword in instead ie
    String query = "SELECT Product FROM Product where Risk IN "+ risk +" and Priority IN "+ priority ;

  • I need help in sql statement

    Hello all,
    im working in hr schema
    i need sql statement to answer my question
    i need all employees information
    where average salary = average salary department 50
    sorry i can't speak english very well
    thank's all

    There is no need to do it in two queries. All you need is:
    select  *
      from  (
             select  e.*,
                     avg(case department_id when 50 then salary end) over() dept_50_avg_sal
               from  hr.employees e
      where salary <= dept_50_avg_sal
    EMPLOYEE_ID FIRST_NAME           LAST_NAME                 EMAIL                     PHONE_NUMBER         HIRE_DATE JOB_ID         SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID DEPT_50_AVG_SAL
            198 Donald               OConnell                  DOCONNEL                  650.507.9833         21-JUN-07 SH_CLERK         2600                       124            50      3475.55556
            199 Douglas              Grant                     DGRANT                    650.507.9844         13-JAN-08 SH_CLERK         2600                       124            50      3475.55556
            115 Alexander            Khoo                      AKHOO                     515.127.4562         18-MAY-03 PU_CLERK         3100                       114            30      3475.55556
            116 Shelli               Baida                     SBAIDA                    515.127.4563         24-DEC-05 PU_CLERK         2900                       114            30      3475.55556
            117 Sigal                Tobias                    STOBIAS                   515.127.4564         24-JUL-05 PU_CLERK         2800                       114            30      3475.55556
            118 Guy                  Himuro                    GHIMURO                   515.127.4565         15-NOV-06 PU_CLERK         2600                       114            30      3475.55556
            119 Karen                Colmenares                KCOLMENA                  515.127.4566         10-AUG-07 PU_CLERK         2500                       114            30      3475.55556
            125 Julia                Nayer                     JNAYER                    650.124.1214         16-JUL-05 ST_CLERK         3200                       120            50      3475.55556
            126 Irene                Mikkilineni               IMIKKILI                  650.124.1224         28-SEP-06 ST_CLERK         2700                       120            50      3475.55556
            127 James                Landry                    JLANDRY                   650.124.1334         14-JAN-07 ST_CLERK         2400                       120            50      3475.55556
            128 Steven               Markle                    SMARKLE                   650.124.1434         08-MAR-08 ST_CLERK         2200                       120            50      3475.55556
    EMPLOYEE_ID FIRST_NAME           LAST_NAME                 EMAIL                     PHONE_NUMBER         HIRE_DATE JOB_ID         SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID DEPT_50_AVG_SAL
            129 Laura                Bissot                    LBISSOT                   650.124.5234         20-AUG-05 ST_CLERK         3300                       121            50      3475.55556
            130 Mozhe                Atkinson                  MATKINSO                  650.124.6234         30-OCT-05 ST_CLERK         2800                       121            50      3475.55556
            131 James                Marlow                    JAMRLOW                   650.124.7234         16-FEB-05 ST_CLERK         2500                       121            50      3475.55556
            132 TJ                   Olson                     TJOLSON                   650.124.8234         10-APR-07 ST_CLERK         2100                       121            50      3475.55556
            133 Jason                Mallin                    JMALLIN                   650.127.1934         14-JUN-04 ST_CLERK         3300                       122            50      3475.55556
            134 Michael              Rogers                    MROGERS                   650.127.1834         26-AUG-06 ST_CLERK         2900                       122            50      3475.55556
            135 Ki                   Gee                       KGEE                      650.127.1734         12-DEC-07 ST_CLERK         2400                       122            50      3475.55556
            136 Hazel                Philtanker                HPHILTAN                  650.127.1634         06-FEB-08 ST_CLERK         2200                       122            50      3475.55556
            138 Stephen              Stiles                    SSTILES                   650.121.2034         26-OCT-05 ST_CLERK         3200                       123            50      3475.55556
            139 John                 Seo                       JSEO                      650.121.2019         12-FEB-06 ST_CLERK         2700                       123            50      3475.55556
            140 Joshua               Patel                     JPATEL                    650.121.1834         06-APR-06 ST_CLERK         2500                       123            50      3475.55556
    EMPLOYEE_ID FIRST_NAME           LAST_NAME                 EMAIL                     PHONE_NUMBER         HIRE_DATE JOB_ID         SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID DEPT_50_AVG_SAL
            142 Curtis               Davies                    CDAVIES                   650.121.2994         29-JAN-05 ST_CLERK         3100                       124            50      3475.55556
            143 Randall              Matos                     RMATOS                    650.121.2874         15-MAR-06 ST_CLERK         2600                       124            50      3475.55556
            144 Peter                Vargas                    PVARGAS                   650.121.2004         09-JUL-06 ST_CLERK         2500                       124            50      3475.55556
            180 Winston              Taylor                    WTAYLOR                   650.507.9876         24-JAN-06 SH_CLERK         3200                       120            50      3475.55556
            181 Jean                 Fleaur                    JFLEAUR                   650.507.9877         23-FEB-06 SH_CLERK         3100                       120            50      3475.55556
            182 Martha               Sullivan                  MSULLIVA                  650.507.9878         21-JUN-07 SH_CLERK         2500                       120            50      3475.55556
            183 Girard               Geoni                     GGEONI                    650.507.9879         03-FEB-08 SH_CLERK         2800                       120            50      3475.55556
            186 Julia                Dellinger                 JDELLING                  650.509.3876         24-JUN-06 SH_CLERK         3400                       121            50      3475.55556
            187 Anthony              Cabrio                    ACABRIO                   650.509.4876         07-FEB-07 SH_CLERK         3000                       121            50      3475.55556
            190 Timothy              Gates                     TGATES                    650.505.3876         11-JUL-06 SH_CLERK         2900                       122            50      3475.55556
            191 Randall              Perkins                   RPERKINS                  650.505.4876         19-DEC-07 SH_CLERK         2500                       122            50      3475.55556
    EMPLOYEE_ID FIRST_NAME           LAST_NAME                 EMAIL                     PHONE_NUMBER         HIRE_DATE JOB_ID         SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID DEPT_50_AVG_SAL
            194 Samuel               McCain                    SMCCAIN                   650.501.3876         01-JUL-06 SH_CLERK         3200                       123            50      3475.55556
            195 Vance                Jones                     VJONES                    650.501.4876         17-MAR-07 SH_CLERK         2800                       123            50      3475.55556
            196 Alana                Walsh                     AWALSH                    650.507.9811         24-APR-06 SH_CLERK         3100                       124            50      3475.55556
            197 Kevin                Feeney                    KFEENEY                   650.507.9822         23-MAY-06 SH_CLERK         3000                       124            50      3475.55556
    37 rows selected.
    SQL> SY.

  • Need Help In SQL Statement

    Hi,
    I need to combine many table only in one select statement.
    This is my table name
    - L20060101
    - L20060102
    - L20060103
    - L20060104
    - L20060105
    - L20060131
    - L20060201
    I dont how to do select statement to select all this table
    This is the wrong select statement.
    Select * from like '%L200601%
    Can i do like that?
    Can any body help me on how to solve my problem?

    You could do something like
    create or replace procedure sp_create_monthly_tabs
         (p_month in varchar2) is
    v_sql varchar2(32767);
    v_cnt number:=0;
    begin
    v_sql := null;
    for c1 in (select table_name from user_tables
    ---   put in the condition to select the tables by the month
    ---  passed in as the parameters
                  ) loop
       if v_cnt = 0 then
          v_sql := 'Create or replace VIEW Mon_Tab'||p_month ||
                       'AS Select * from '||C1.Table_Name ||' ' ;
       else
          v_sql := v_sql||'Union All '||'Select * from '||C1.Table_Name ||' ' ;
       end if;
       v_cnt := v_cnt + 1;
    end loop;
    execute immediate(v_sql)
    end;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Need help creating SQL Query

    Hi,
    I have this table
    declare @t_date table(cut_off datetime)
    insert into @t_date
    select '20140930'
    union
    select '20140716'
    union
    select '20140715'
    union
    select '20140714'
    union
    select '20140627'
    union
    select '20140625'
    I need this result: Dates nearests to end of month
    In the table on example, I need this output
    2014-09-30
    2014-07-16
    2014-06-27
    Can anyone help me?
    Thanks a lot in advance.
    declare @t_date table(cut_off datetime)
    insert into @t_date
    select '20140930' --this is OK cause eom
    union
    select '20140716' --this is OK cause is the nearest to eom(07)
    union
    select '20140715' --this is KO cause is not the nearest to eom(07)
    union
    select '20140714' --this is KO cause is not the nearest to eom(07)
    union
    select '20140627' --this is OK cause is the nearest to eom(06)
    union
    select '20140625' --this is KO cause is not the nearest to eom(06)

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. You have no keys! Learn how to follow ISO-11179 data element naming conventions and formatting rules.
    Temporal data should use ISO-8601 formats. It is the only –- repeat, only -– format allowed in ANSI/ISO Standard SQL! Code should be in Standard SQL as much as possible and not local dialect. We would use the correct INSERT INTO syntax. 
    Oh, that silly “t_” is called a “tibble” and we laugh at it. 
    CREATE TABLE Foobar_Dates
    (foobar_date DATE NOT NULL PRIMARY KEY);
    INSERT INTO Foobar_Dates
    VALUES
    ('2014-06-25'),
    ('2014-06-27'),
    ('2014-07-14'),
    ('2014-07-15'),
    ('2014-07-16'),
    ('2014-09-30'),
    >> I need this result: for each month I need the date nearest to end of month <<
    Since SQL is a database language, we prefer to do look ups and not calculations. They can be optimized while temporal math messes up optimization. A useful idiom is a report period calendar that everyone uses so there is no way to get disagreements in the DML.
    Build good tools and re-use them! 
    The report period table gives a name to a range of dates that is common to the entire enterprise. 
    CREATE TABLE Month_Periods
    (month_name CHAR(10) NOT NULL PRIMARY KEY
       CHECK (month_name LIKE '[12][0-9][0-9][0-9]-[01][0-9]-00'),
     month_start_date DATE NOT NULL,
     month_end_date DATE NOT NULL,
      CONSTRAINT date_ordering
        CHECK (month_start_date < month_end_date),
    etc);
    These report periods can overlap or have gaps. I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantages are that it will sort with the ISO-8601
    data format required by Standard SQL and it is language independent. 
    SELECT M.month_name, MAX(F.foobar_date), 
           OVER (PARTITION BY M.month_name)
      FROM Foobar_Dates AS F, 
           Month_Periods AS M 
     WHERE F.foobar_date BETWEEN M.month_start_date AND M.month_end_date;
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Help with SQL statements please.... URGENT PLEASE!!!!

    I have 2 Tables
    TABLE_NAME COLUMN_NAME DATA_TYPE
    TASTEWINE TWDATE DATE
    TASTEWINE BIN NUMBER
    TASTEWINE QUANTITY NUMBER
    TASTING TDATE DATE
    TASTING PLACE VARCHAR2
    a) Table TASTING has 2 columns.... TDATE( date Tasting was Held) and PLACE ( locations at which Tasting was held)
    b) Table TASTEWINE has 3 Columns.............. TWDATE( wine tasting date, BIN( ID number for type of wine that was tasted), AND QUANTITY( quantity of win consumed by bottles)
    Here is the QUestion.... I am having a hard time figuring out how to connect those two tables based on this information .. What I want to do is this.....select the total number of bottles of wine served at each wine-tasting, but only for the second half of the year 1999, and I want to see not only the date and total bottles served, but also the location where the wine-tasting took place. I also want to display the date, the place, and total quantity.
    Can Anyone please Help me??

    Hi,
    Your query works fine - as well as the one mentioned by Alok. I have tired it with some sample values, and both show the same results:-
    The two tables :-
    CREATE TABLE TASTEWINE
         TWDATE     DATE,
         BIN     NUMBER,
         QUANTITY NUMBER
    CREATE TABLE TASTING
         TDATE DATE,
         PLACE VARCHAR2(100)
    );Rows in the Tables:-
    INSERT INTO TASTEWINE VALUES (TO_DATE('01/12/1999','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('02/12/1999','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('03/12/1999','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('04/12/1999','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('05/12/1999','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('06/12/1999','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('07/12/1999','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('08/12/1999','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('09/12/1999','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('10/12/1999','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('11/12/1999','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('12/12/1999','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('01/12/2000','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('02/12/2000','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('03/12/2000','MM/DD/YYYY'),1,100);
    INSERT INTO TASTEWINE VALUES (TO_DATE('04/12/2000','MM/DD/YYYY'),1,100);
    COMMIT;
    INSERT INTO TASTING VALUES (TO_DATE('01/12/1999','MM/DD/YYYY'),'SEATTLE');
    INSERT INTO TASTING VALUES (TO_DATE('02/12/1999','MM/DD/YYYY'),'SAN FRANSICO');
    INSERT INTO TASTING VALUES (TO_DATE('03/12/1999','MM/DD/YYYY'),'DENVER');
    INSERT INTO TASTING VALUES (TO_DATE('04/12/1999','MM/DD/YYYY'),'AUSTIN');
    INSERT INTO TASTING VALUES (TO_DATE('05/12/1999','MM/DD/YYYY'),'SALT LAKE CITY');
    INSERT INTO TASTING VALUES (TO_DATE('06/12/1999','MM/DD/YYYY'),'LOS ANGLES');
    INSERT INTO TASTING VALUES (TO_DATE('07/12/1999','MM/DD/YYYY'),'PORTLAND');
    INSERT INTO TASTING VALUES (TO_DATE('08/12/1999','MM/DD/YYYY'),'NEW YORK');
    INSERT INTO TASTING VALUES (TO_DATE('09/12/1999','MM/DD/YYYY'),'NEWARK');
    INSERT INTO TASTING VALUES (TO_DATE('10/12/1999','MM/DD/YYYY'),'EL PASO');
    INSERT INTO TASTING VALUES (TO_DATE('11/12/1999','MM/DD/YYYY'),'AUSTIN');
    INSERT INTO TASTING VALUES (TO_DATE('12/12/1999','MM/DD/YYYY'),'CHICAGO');
    INSERT INTO TASTING VALUES (TO_DATE('01/12/2000','MM/DD/YYYY'),'ATLANTA');
    INSERT INTO TASTING VALUES (TO_DATE('02/12/2000','MM/DD/YYYY'),'HOLLYWOOD');
    INSERT INTO TASTING VALUES (TO_DATE('03/12/2000','MM/DD/YYYY'),'');
    INSERT INTO TASTING VALUES (TO_DATE('04/12/2000','MM/DD/YYYY'),'SEATTLE');
    COMMIT;The First Query :-
    SELECT
         A.TWDATE,
         B.PLACE,
         SUM(A.QUANTITY)
    FROM
         TASTEWINE     A,
         TASTING          B
    WHERE
              A.TWDATE = B.TDATE
         AND     B.TDATE > TO_DATE('01/07/1999', 'DD/MM/YYYY')
         AND     B.TDATE < TO_DATE('01/01/2000', 'DD/MM/YYYY')
    GROUP BY
         A.TWDATE,
         B.PLACE;The Second Query :-
    SELECT
         A.TWDATE,
         B.PLACE,
         SUM(A.QUANTITY)
    FROM
         TASTEWINE     A,
         TASTING          B
    WHERE
              A.TWDATE = B.TDATE
         AND     B.TDATE
                   BETWEEN
                        TO_DATE('01/07/1999', 'DD/MM/YYYY')      AND
                        TO_DATE('01/01/2000', 'DD/MM/YYYY')
    GROUP BY
         A.TWDATE,
         B.PLACE;Regards,
    Sandeep

  • Need Help: Complex SQL statement

    select segment3, 0 "Other Income"
         , 0 "Sales of Services"
         , 0 "Personnel Costs"
         , 0 "Other Staff Cost"
         , 0 "General Admin"
         , 0 "Travel"
         , 0 "Collaborator"
         , 0 "Training"
         , 0 "Capital"     
         , nvl(round(sum (nvl(PERIOD_ACTIVITY_A,0) + nvl(PERIOD_ACTIVITY_E,0) + nvl(PRDOPEN_A,0) + nvl(PRDOPEN_E,0)),0),0) "Overhead"
         , 0 "Finance Charges"
         from PAYMAN.SNP_OP_DETAIL@OFA
         where segment3= x.new_cc and period_name = p_period
         and segment2 in (select acc_t from CRP_REPORT_ACCT_DETAIL_T where group_id = 10)
         group by segment3
    Please I don't understand select segment3, 0 "Other Income"....there's no column called 0, what is the 0s doing in the select statement?
    Secondly, I don't understand from PAYMAN.SNP_OP_DETAIL@OFA

    Hi,
    OlaTunde wrote:
    select segment3, 0 "Other Income"
         , 0 "Sales of Services"
         , 0 "Personnel Costs"
         , 0 "Other Staff Cost"
         , 0 "General Admin"
         , 0 "Travel"
         , 0 "Collaborator"
         , 0 "Training"
         , 0 "Capital"     
         , nvl(round(sum (nvl(PERIOD_ACTIVITY_A,0) + nvl(PERIOD_ACTIVITY_E,0) + nvl(PRDOPEN_A,0) + nvl(PRDOPEN_E,0)),0),0) "Overhead"
         , 0 "Finance Charges"
         from PAYMAN.SNP_OP_DETAIL@OFA
         where segment3= x.new_cc and period_name = p_period
         and segment2 in (select acc_t from CRP_REPORT_ACCT_DETAIL_T where group_id = 10)
         group by segment3
    Please I don't understand select segment3, 0 "Other Income"....there's no column called 0, what is the 0s doing in the select statement?Columns are one of the expressions that can be in a SELECT clause. There are many other kinds of expressions, including liteals (as in this example), pseudo-columns, functions, and compound expressions that are also allowed.
    Consider the following query:
    SELECT       deptno          AS raw_detpno
    ,       1 + deptno          AS one_plus
    ,       0 + deptno          AS zero_plus
    ,       0                  AS zero
    FROM       scott.dept
    ORDER BY  deptno
    ;Output:
    RAW_DETPNO   ONE_PLUS  ZERO_PLUS       ZERO
            10         11         10          0
            20         21         20          0
            30         31         30          0
            40         41         40          0No doubt you're familiar with using table columns (such as deptno) by themselves as an expression, as in the output column raw_deptno.
    You're probably familiar with using a table column and a numeric literal together, as in the ouptuput columns one_plus and zero_plus.
    It's also allowed to use numeric literals by themselves, as in the output column called zero.
    Expressions are part of the SQL language, so you can read about them in the SQL language manual:
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/expressions001.htm#sthref1844
    Secondly, I don't understand from PAYMAN.SNP_OP_DETAIL@OFA@OFA is a database link. See
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/queries010.htm#sthref2287

  • Help creating sql and concatenating column.

    hello i have a table that looks like this
    CREATE TABLE "TEST1"
       (    "TEST1_ROLE" VARCHAR2(100 BYTE),
        "TEST1_VENDOR_NUMBER" VARCHAR2(100 BYTE)
    it has this data
    INSERT INTO "TEST1" (TEST1_ROLE, TEST1_VENDOR_NUMBER) VALUES ('student', '910241630')
    INSERT INTO "TEST1" (TEST1_ROLE, TEST1_VENDOR_NUMBER) VALUES ('staff', '910241630')
    INSERT INTO "TEST1" (TEST1_ROLE, TEST1_VENDOR_NUMBER) VALUES ('employee', '910241630')
    i would like to create a query where i basically summarize based on vendor _number and i would end up with all the roles in one row
    like this
    910241630     student,staff, employee
    I'm having a very difficult time trying to acomplish this can someone please give me a pointer on how i would acomplish this.

    Hi,
    That sounds like a job for the aggregate LISTAGG function:
    SELECT    test1_vendor_number
    ,         LISTAGG (test1_role, ', ') WITHIN GROUP (ORDER BY test1_role) AS role_list
    FROM      test1
    GROUP BY  test1_vendor_number
    This will produce a separate row of output for each distinct test1_vendor_number.

  • Help about SQL statement

    There is one table AA£º
    A varchar2(10);--goods name
    B number(30);--amount
    C date;--date
    There are millions of records in the table, now to calculate the top ten good's acount and total amount, could you pls tell me how to do it?
    by using
    select A,count(A),sum(B) from AA group by A order by sum(B)
    it's extermely slow. Could you pls tell me how to optimize it, Thank you very much

    Now I understand better your concern. It's about "to use, or not to use" a materialized view for your query.
    I listed bellow a basic example of using of a materialized view, reusing the tables from my previous sample. Note that the table "bb" has a MV, while table "bb1" is without MV.
    The results are very clear simple, and similar results can be expected for many similar cases. Note that the Oracle manuals warn us about this, but it is using words which are not strong enough.
    1. The INSERT is about 20 times slower in the presence of MVs. The usage of many small transactions is probably slower then fewer and larger transactions. Note that the MVs usage increase considerably the duration of locking, affecting negatively the level of concurrency, and increases the storage requirements.
    2. The SELECT from your aggregate query is about 15 times faster when using a dedicated MV. But many other other SELECT queries are not made faster by this MV, obviously.
    This is the reason for which the MVs are generally not well suited in transactional environments, with a lot of frequent data updates and many different queries, but play a major role in DSS environments. The MVs are still useful in some transactional applications, where long running queries are executed frequently (but your query does not seem to be in this situation).
    create table bb0 as select * from bb where rownum <= 1000000;
    truncate table bb;
    create table bb1 as select * from bb0 where rownum < 1
    create materialized view log on bb
    with sequence, rowid
    (a, b)
    including new values;
    create materialized view bb_mv
    build immediate refresh fast on commit
    as (select a, count(*) c, count(*) c1, sum(b) s from bb group by a);
    insert into bb
    select *
    from (select * from bb0 order by b)
    where rownum <= 1000000;
    1000000 rows inserted
    executed in 180.579 seconds <<==
    commit;
    executed in 123.838 seconds <<==
    insert into bb1
    select *
      from (select * from bb0 order by b)
    where rownum <= 1000000;
    1000000 rows inserted
    executed in 15.182 seconds <<==
    commit;
    executed in 0.01 seconds
    select *
      from (select a, c, s from bb_mv order by 3 desc)
    where rownum <= 10;
    10 rows selected
    executed in 0.16 seconds  <<==
    select *
      from (select a, count(a), sum(b) from bb1 group by a order by 3 desc)
    where rownum <= 10;
    10 rows selected
    executed in 2.373 seconds <<==

Maybe you are looking for