Help SQL query Join

EXAMPLES OF DATA-

CREATE TABLE ITEM_GRP (ITEM_GRP_ID int NOT NULL, ITEM_ID int, GRP_NAME VARCHAR2 (100),)

PRIMARY KEY (ITEM_GRP_ID),

FOREIGN KEY (ITEM_ID) REFERS TO ITEM_1 (ITEM_ID));

CREATE TABLE TABLE_1 (int A_ITEM_ID, int B_ITEM_ID, VARCHAR2 (100) DESCRIPTION,)

PRIMARY KEY (A_ITEM_ID),

FOREIGN KEY (A_ITEM_ID) REFERENCES ITEM_1 (ITEM_ID),

FOREIGN KEY (B_ITEM_ID) REFERS TO ITEM_1 (ITEM_ID));

INSERT INTO ITEM_1 (ITEM_ID, DESCRIPTION) VALUES (1, 'ITEM1');

INSERT INTO ITEM_1 (ITEM_ID, DESCRIPTION) VALUES (2, 'ITEM2');

INSERT INTO ITEM_1 (ITEM_ID, DESCRIPTION) VALUES (3, 'ITEM3');

INSERT INTO ITEM_1 (ITEM_ID, DESCRIPTION) VALUES (4, "ITEM4");

INSERT INTO ITEM_1 (ITEM_ID, DESCRIPTION) VALUES (5, "ITEM5");

COMMIT;

INSERT INTO ITEM_GRP (ITEM_GRP_ID, ITEM_ID, GRP_NAME) VALUES (10, 1, 'ITEM1 GRP');

INSERT INTO ITEM_GRP (ITEM_GRP_ID, ITEM_ID, GRP_NAME) VALUES (11, 2, 'ITEM2 GRP');

INSERT INTO ITEM_GRP (ITEM_GRP_ID, ITEM_ID, GRP_NAME) VALUES (12, 2, 'ITEM2 GRP');

COMMIT;

INSERT INTO TABLE_1 (A_ITEM_ID, B_ITEM_ID, DESCRIPTION) VALUES (2, 1, ' Description point 2');

INSERT INTO TABLE_1 (A_ITEM_ID, B_ITEM_ID, DESCRIPTION) VALUES (3, 1, ' Description point 3');

INSERT INTO TABLE_1 (A_ITEM_ID, B_ITEM_ID, DESCRIPTION) VALUES (4, 1, ' Description point 4');

INSERT INTO TABLE_1 (A_ITEM_ID, B_ITEM_ID, DESCRIPTION) VALUES (5, 1, ' Description point 5');

COMMIT;

The scenario is, there are three tables - ITEM_1, ITEM_GRP, TABLE_1. The order of the DAY is the main table for all items.

SELECT * FROM TABLE_1 where B_ITEM_ID = 1;

DESCRIPTION OF B_ITEM_ID A_ITEM_ID

---------- ---------- ----------------------------------------------------------------------------------------------------

2 1 description point 2

3 1 description of the point 3

4 1 description of the point 4

5 1 description of point 5

Now the query I try to write should return 1 (or count (*) = 1) if

-TABLE_1.A_ITEM_ID = ITEM_GRP. ITEM_ID and have > 1

In this case, the assigned action returned 4 rows and even if there is a match with A_ITEM_ID = 2 which exist on ITEM_GRP twice, he was no match for other A_ITEM_ID in the ITEM_GRP table. If the query should return 0 or null.

Here is what I started with.

SELECT * FROM ITEM_GRP IG, M TABLE_1

WHERE IG. ITEM_ID (+) = M.A_ITEM_ID

AND M.B_ITEM_ID = 1

- AND IG. ITEM_ID IS NULL

- AND EXISTS (SELECT 1 FROM ITEM_GRP WHERE ITEM_ID = IG. ITEM_ID HAVING COUNT (*) > 1)

(Working on it)

Oracle Version-

Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - production

PL/SQL Release 10.2.0.4.0 - Production

CORE 10.2.0.4.0 Production

AMT for 32-bit Windows: release 10.2.0.4.0 - Production

NLSRTL Version 10.2.0.4.0 - Production

Hello

Here's a way to do it:

SELECT THE CHECK BOX

WHEN MIN (COUNT (ig.item_id)) > = 2

THEN 1

0 OTHERWISE

END AS all_2

FROM table_1 t1

LEFT OUTER JOIN item_grp ON ig.item_id = t1.a_item_id GI

GROUP BY t1.a_item_id

;

The outer join will ensure that all values of table_1.a_item_id are selected.

COUNT (item_grp.item_id) will indicate the number of lines corresponding to each value of a_item_id.  Since it is an outer join, this number may be 0.

If (and only if) the a_item_ids has 2 or more matches, then these counts of 2 minutes or more.

Tags: Database

Similar Questions

  • Need help for query joining views

    Hi all

    I need to run a query that joins a number of tables with multiple instances of the same view.  For example, a view named MY_VALUES, is an array of key / value resembles the following:

    Application_ID Attirbute_Description value

    1 1 000 basic benefit

    1 multiplier 1 0.5

    1 Multiplier_2 1.2

    1 total profit 1,115

    2 1 025 basic benefit

    2 multiplier 1 0,268

    2 Multiplier_2 1.3

    Total profit 2 1.4500

    Say I want a query that selects basic earnings and a multiplier 1 for Application ID 1, as well as, other information from a table called APPLICATION that has a relationship to display pk - fk. I would do the following:

    Select the application. Name, mv1.value, mv2.value

    from dbo. App APPLICATION, dbo. MY_VALUES mv1, dbo. Mv2 MY_VALUES

    where app.id = mv1.application_id and mv1.attribute_description = "Basic benefits"

    and app.id = mv2.application and mv2.attribute_description = id 'multiplier 1'.

    and app.id = 1

    My actual query is similar to this. However, I have many other attributes of the notice I need to select, which requires that the view be attached to several times. After 16 these joins, the request is fine. After 17, however, the query runs always, never return a result within 45 minutes I have let it run.

    Is there a better way to write such a request or an indicator of optimization that would be useful here?

    Any help is greatly appreciated.

    ....

    For this type of application, it is often best to extract multiple lines in a single request on the view and their pivot in the output.

    For example

    Select the application. Name

    , max (CASE when mv.attribute_description = "Core service" then mv.value any other purpose) BaseBenefit

    , max (CASE when mv.attribute_description = 'Multiplier 1' then mv.value any other purpose) Multiplier1

    , max (CASE when mv.attribute_description = 'Multiplier 2' then mv.value any other purpose) Multiplier2

    , max (CASE when mv.attribute_description = 'Multiplier 3' then mv.value end to another null) Multiplier3

    from dbo. App APPLICATION, dbo. MY_VALUES mv

    where app.id = mv1.application_id

    and mv.attribute_description IN ('benefits of home', 'multiplier 'multiplier 'multiplier 3' 2' 1')

    and app.id = 1

    This runs often much better than several joins to the table for the view or the value of the attribute.

  • Need help SQL - query data-

    Hello

    I am trying to query data in my database to do the following...

    ' Create a query to show all members of the staff who were working on a Monday and worked for more than 86 weeks.

    I did the following and it works...

    SELECT employe_id, Employee_Name, Hire_Date
    The EMPLOYEE
    WHERE months_between(sysdate,Hire_Date) > 12 * 1.52;

    The query returns all that was necessarily over 86 weeks.

    What I would do, is to understand Monday in the query, but I don't know how to do this.

    Could someone help?

    -Try this:

    SELECT employe_id, Employee_Name, Hire_Date
    The EMPLOYEE
    WHERE months_between(sysdate,Hire_Date) > 12 * 1.52
    and to_char (hire_date, 'fmDAY') = 'MONDAY ';

    Published by: P@K on April 14, 2009 18:26

  • Need help SQL query

    Hi all

    CREATE TABLE PXX_CUST_TABLE

    (NUMBER OF PERSON_ID,

    DATE OF DATE_START,

    DATE OF DATE_END,

    ATTRIBUTE1 VARCHAR2 (30),

    ATTRIBUT2 VARCHAR2 (30),

    ATTRIBUT3 VARCHAR2 (30))

    Insert into PXX_CUST_TABLE

    (PERSON_ID, DATE_START, DATE_END, ATTRIBUT1, ATTRIBUT2, ATTRIBUT3)

    Values

    (3619, TO_DATE (1 JULY 2015 00:00:00 ',' ' HH24:MI:SS JJ/MM/AAAA), TO_DATE (27 JULY 2015 00:00:00 ',' MM/DD/YYYY HH24:MI:SS'), ' 2015/07/12 00:00:00 ', ' 2015/07/13 00:00:00 ', ' 2015-07-14 00:00:00 ');

    Insert into PXX_CUST_TABLE

    (PERSON_ID, DATE_START, DATE_END, ATTRIBUT1, ATTRIBUT2, ATTRIBUT3)

    Values

    (3619, TO_DATE (1 JULY 2015 00:00:00 ',' ' HH24:MI:SS JJ/MM/AAAA), TO_DATE (JULY 30, 2015 00:00:00 ',' MM/DD/YYYY HH24:MI:SS'), ' 2015/07/01 00:00:00 ', ' 2015/07/05 00:00:00 ', ' 2015/07/07 00:00:00 ');

    Insert into PXX_CUST_TABLE

    (PERSON_ID, DATE_START, DATE_END, ATTRIBUT1, ATTRIBUT2, ATTRIBUT3)

    Values

    (3619, TO_DATE (AUGUST 1, 2015 00:00:00 ',' ' HH24:MI:SS JJ/MM/AAAA), TO_DATE (AUGUST 22, 2015 00:00:00 ',' MM/DD/YYYY HH24:MI:SS'), ' 2015/08/01 00:00:00 ', ' 2015/08/02 00:00:00 ', ' 2015-08-09 00:00:00 ')

    Insert into PXX_CUST_TABLE

    (PERSON_ID, DATE_START, DATE_END, ATTRIBUT1, ATTRIBUT2, ATTRIBUT3)

    Values

    (3619, TO_DATE (AUGUST 1, 2015 00:00:00 ',' ' HH24:MI:SS JJ/MM/AAAA), TO_DATE (AUGUST 29, 2015 00:00:00 ',' MM/DD/YYYY HH24:MI:SS'), ' 2015/08/03 00:00:00 ', ' 08/2015/04 00:00:00 ', ' 2015/08/05 00:00:00 ');

    COMMIT;

    SELECT * FROM PXX_CUST_TABLE

    PERSON_ID DATE_START, DATE_END ATTRIBUTE1 ATTRIBUT2 ATTRIBUT3

    3619 12/07/2015 27/07/2015 2015/07/01 00:00:00 00:00:13 / 07/2015 00 2015-07-14 00:00:00

    3619 01/07/2015 30/07/2015 2015/07/01 00:00:00 00:00:05 / 07/2015 00 2015/07/07 00:00:00

    3619 01/08/2015 22/08/2015 2015/08/01 00:00:00 00:00:02 / 08/2015 00 2015-08-09 00:00:00

    3619 03/08/2015 29/08/2015 2015/08/01 00:00:00 00:00:04 / 08/2015 00 2015/08/05 00:00:00

    Requirement:

    You want to count the dates (attributes) only if the parameter falls between date_start and date_end.

    Tested:

    Select sum (attribut1, attribut2 + attribut3) Total_days

    Of

    (

    Select

    person_id, date_start, date_end,

    -CHECK WITH THE CASE IF THE DATES OF THE ATTRIBUTE HAS ENTERED FALLS DATES IN THE GIVEN INTERVAL

    cases where TO_DATE (SUBSTR (attribute1, 1, 10), ' YYYY/MM/DD') between TO_DATE('27-JUL-2015') AND TO_DATE('10-SEP-2015') then 1 end attribute1

    case when TO_DATE (SUBSTR (attribute2, 1, 10), ' YYYY/MM/DD') between TO_DATE('27-JUL-2015') AND TO_DATE('10-SEP-2015') then 1 end attribut2

    case when TO_DATE (SUBSTR (attribute3, 1, 10), ' YYYY/MM/DD') between TO_DATE('27-JUL-2015') AND TO_DATE('10-SEP-2015') then 1 end attribut3

    -Intended for don't check unique records

    Of

    PXX_CUST_TABLE

    where DATE_START BETWEEN TO_DATE('27-JUL-2015') AND TO_DATE('10-SEP-2015')

    and DATE_END BETWEEN TO_DATE('27-JUL-2015') AND TO_DATE('10-SEP-2015')

    )

    Output:

    Total_days

    6

    Output must be 5 as date "01/08/2015 ' is twice as much."

    Please suggest.

    Kind regards

    Afzal.

    with

    pxx_cust_table as

    (select 3619 person_id, to_date('07/01/2015','mm/dd/yyyy') date_start, to_date('07/27/2015','mm/dd/yyyy') date_end, to_date('2015/07/12','yyyy/mm/dd') attribute1, attribute2, to_date('2015/07/14','yyyy/mm/dd') attribut3 of all to_date('2015/07/13','yyyy/mm/dd') the double union)

    Select 3619, to_date (' 07/01/2015 ',' mm/dd/yyyy'), to_date (' 07/30/2015 ',' mm/dd/yyyy'), to_date('2015/07/01','yyyy/mm/dd'), to_date('2015/07/05','yyyy/mm/dd'), to_date('2015/07/07','yyyy/mm/dd') in all the double union

    Select 3619, to_date (' 01/08/2015 ',' mm/dd/yyyy'), to_date (' 08/22/2015 ',' mm/dd/yyyy'), to_date('2015/08/01','yyyy/mm/dd'), to_date('2015/08/02','yyyy/mm/dd'), to_date('2015/08/09','yyyy/mm/dd') in all the double union

    Select 3619, to_date('08/01/2015','mm/dd/yyyy'), to_date('08/29/2015','mm/dd/yyyy'), to_date('2015/08/01','yyyy/mm/dd'), to_date('2015/08/04','yyyy/mm/dd'), double to_date('2015/08/05','yyyy/mm/dd')

    )

    Select person_id, count (distinct attribute_value) count_distinct

    (select person_id, attribute_name and attribute_value

    of pxx_cust_table

    UNPIVOT (attribute_name attribute_value in (attribut1 1, attribut2 as 2, attribut3 3))

    )

    where attribute_value between date "2015-07-27' and the date ' 2015-09-10. '"

    Person_id group

    PERSON_ID COUNT_DISTINCT
    3619 5

    Concerning

    Etbin

  • Help with time operations invloving the SQL query

    I created 2 tables in my SQL. One is the user_info_table table that stores the connection time and time zone of login for each user. The other is the post_table that stores user postid, who makes the post time post and time zone for each message.
    CREATE TABLE user_info
    (
    user_id VARCHAR(20), 
    login_date DATE,
    login_time_zone VARCHAR(20),
    PRIMARY KEY (user_id)
    );
    CREATE TABLE post_table
    (
    post_id VARCHAR(20),  
    user_id VARCHAR(20), 
    datepost DATE,  
    time_zone VARCHAR(20),
    PRIMARY KEY (post_id),
    FOREIGN KEY (user_id) REFERENCES user_info(user_id) ON DELETE CASCADE
    ) ;
    Some examples of data for my paintings is as below.
    INSERT INTO user_info VALUES( 'u1', to_date('9/17/2009 20:00','MM/DD/YYYY mi:ss'), -2 );
    INSERT INTO user_info VALUES( 'u2', to_date('9/17/2009 19:55','MM/DD/YYYY mi:ss'), -4 );
    
    INSERT INTO post_table VALUES( 'p1', 'u1', to_date('9/17/2009 20:50','MM/DD/YYYY mi:ss'), 6 );
    INSERT INTO post_table VALUES( 'p2', 'u2', to_date('9/17/2009 20:30','MM/DD/YYYY mi:ss'), -5 );
    INSERT INTO post_table VALUES( 'p3', 'u2', to_date('9/18/2009 6:00','MM/DD/YYYY mi:ss'), 2 );
    INSERT INTO post_table VALUES( 'p4', 'u1', to_date('9/17/2009 21:00','MM/DD/YYYY mi:ss'), -3 );
    I need to write a SQL query which - is the user whose time difference between the time of the connection and the last time when he or she wrote a post is the smallest. I need to consider the time zones here as well.

    I am not sure if time_zone must be of type VARCHAR or TIMESTAMP then have created as a VARCHAR in my paintings.

    Someone help me please to form this query.

    PS: How can I tags < code > user in this forum to write sql statements.

    Published by: user11994430 on October 9, 2009 17:59

    You can do this by adding a clause of "HAVING" as shown below. However, with your test defined data it returns ZERO rows because for all users of the MAX (DATEPOST) IS LESS than MAX (LOGIN_DATE)

    SELECT     USER_ID
    FROM
    (
         SELECT     USER_ID
         ,     DENSE_RANK() OVER (ORDER BY POST_LOGIN_DIFF) RNK
         FROM
         (
              SELECT     USER_INFO.USER_ID
              ,     MAX(DATEPOST) - MAX(LOGIN_DATE) AS POST_LOGIN_DIFF
              FROM     USER_INFO
              JOIN     POST_TABLE     ON POST_TABLE.USER_ID = USER_INFO.USER_ID
              GROUP BY USER_INFO.USER_ID
              HAVING      MAX(DATEPOST) > MAX(LOGIN_DATE)
         )
    )
    WHERE RNK = 1
    
  • Query Join help

    Hello:

    I need help to write my side of my SQL statement join.

    I have four tables with the following fields. The State tables, specialty and Classification are just tables of research.
    1 Organization->
    -ORG_KEY (PK) NOT NULL default (null)
    -STATE_KEY (FK) NOT NULL default (null)
    -SPECIALITY_KEY (FK) NOT NULL default (null)
    -CLASSIFICATION_KEY (FK) default NULL (null)

    2 State->
    -STATE_KEY (PK) NOT NULL default (null)
    -NAME NOT NULL default (null)
    -CODE NON default NULL (null)

    3 specialty->
    -SPECIALITY_KEY (PK) NOT NULL default (null)
    -NAME NOT NULL default (null)
    -CODE NON default NULL (null)

    4 classification-->
    -CLASSIFICATION_KEY (PK) default NULL (null)
    -NAME NOT NULL default (null)
    -CODE NON default NULL (null)

    When I run my select (using SQL Developer) and the SPECIAILITY_KEY and CLASSIFICATION_KEY fields are NOT filled (they have a null value appear as their value), I get no results and in the Express Application, I get an error message indicating "no data found".

    At the point where I have enter values in these two areas, the query returns records lines.

    When I try to insert a record and do not include a value for SPECIALITY_KEY and CLASSIFICATION_KEY, I get the following error message:
    ORA-01400: cannot insert NULL into ('TEST'. "ORGANIZATION '." "" ""CLASSIFICATION_KEY")."

    This is my SELECT statement:
    select a.org_key, 
         e.org_key||' - '|| e.name as parent, 
         e.name as name1, 
         a.sponsor, a.subscriber, a.provider,
         a.is_legal_entity,
         a.short_name, a.name, a.status, a.external_id, a.tin, a.region,
         a.address_line_1,a.address_line_2, a.city, 
         b.state_cd||' - '|| b.name as state, a.zip,
         a.zip_plus_four, a.live_date, a.contact_salutation, a.contact_first_name,
         a.contact_middle_initial, a.contact_last_name, a.contact_name_suffix,
         a.contact_email_address, a.primary_phone, a.primary_phone_ext,
         a.other_phone, a.other_phone_ext, a.fax_no, a.website_url, 
         a.web_org_type, a.created_date, a.created_by, a.last_update_date,
         a.last_updated_by,
         c.classification_key||' - '|| c.name as classification,
         d.speciality_key||' - '|| d.name as speciality,
         a.bill_address_line_1, a.bill_address_line_2, a.bill_city,
         b.state_cd||' - '|| b.name as bill_state, a.bill_zip,
         a.bill_zip_plus_four, a.dwkey_org
    
    from mdd.organization a,
         mdd.state b,
         mdd.org_classification c,
         mdd.speciality d,
         mdd.organization e
    
    where a.state_key = b.state_key   
      and a.classification_key = c.classification_key
      and a.speciality_key = d.speciality_key
     and a.parent_org_key = e.org_key
    If I do not write the WHERE clause with all joints, I received several entries for the same record. With this WHERE clause, my query returns one record per org_key.

    Now, at the time where the user creates an org, the user can ignore the specialty or classification so they would be leave the field blank. It is a legitimate situation.
    How can I write my application so if a null value appears in a field, I always get the results?

    I would like to see all of my folders without worrying if the fields have a real value or display a NULL value. Showing records that have a NULL value, the user can see what information is missing and later come back and enter.

    Can someone help me?
    Thank you.

    Hello

    The CREATE TABLE instructions work when you run? I get a lot of errors, lack of parentheses and commas. Also, many to INSERT it IN the ORGANIZATION of statements fail because the parent records are missing. To get things to work, I ignored all the constraints.

    To change your original query so that all ranks of orgainaztion appears, if it has a corresponding line in any other tables, maike all the join conditions outer joins. For example:

     where a.state_key = b.state_key                  (+)
      and a.classification_key = c.classification_key (+)
      and a.speciality_key = d.speciality_key         (+)
     and a.parent_org_key = e.org_key            (+)
    

    If a match is not in any of the tables b, c, d or e, all columns of the table without a match will be displayed with a NULL value.

  • Please help build a sql query

    Hello

    Please help build a sql query


    My Table Test2015 has given below

    Header_id Line_id Ordered_item       

    723887290 199925 MAIN1

    199925 723887291 MAIN2

    199926 723887292 SH-POS-NO-BR POS-INS

    199926 723887293 MAIN2

    199927 723887294 IC-ENV-NON-BR-ENV-PXY

    199927 723887295 MAIN1

    199927 723887297 MAIN2

    199927 723887298 PRCSS SH-FAIRY-ELEC DISTR.

    199927 723887299 SH-FAIRY-SUM PRO-DE-CONS-HOUSE

    I am trying to query my Test2015 table to obtain the records with ordered_item containing 'MAIN1' and 'MAIN2' only. I tried to write a query as below

    SELECT * FROM test2015 WHERE ORDERED_ITEM in ('MAIN1', 'MAIN2');

    But it gives me all the data with the MAIN2 records found but MAIN1 is absent, I want to retrieve only records to both 'MAIN1' and 'MAIN2' present for Header_id.

    While the result below shows me header_id - 199926 and 199929 that he should assume back. I want to fetch documents only with 'MAIN1' and 'MAIN2' both present.

    Header_id Line_id Ordered_item            

    723887290 199925 MAIN1

    199925 723887291 MAIN2

    199926 723887293 MAIN2

    199927 723887295 MAIN1

    199927 723887297 MAIN2

    199929 723887299 MAIN1

    Please suggest.

    Thank you and best regards,

    Prasad.

    Hello

    Try like this...

    SELECT * FROM test2015 WHERE ORDERED_ITEM in ('MAIN1") and in header_id (select test2015 WHERE ORDERED_ITEM in ('MAIN2') header_id)

  • Need help with a SQL query

    Hello

    I have a data in table (raj_table) with columns (char11) raj_id, raj_number (varchar2 (15)), raj_format (NUMBER), Primary_ID (identity with the values of the primary key column)

    Primary_ID raj_id Raj_number Raj_format

    1                            raj                 rajvend                      1

    2                            raj                 rajvend                      1

    3                            raj                 rajvendor1                 2

    4                            raj                 rajvendor1                 2

    5                            raj                 rajvendor1                 2

    6                            raj                 rajvendor2                 3

    I used under SQL to get query output as below, but has not achieved the required result:

    Select client_id vendor_number, vendor_format, primary_id, row_number() on sl_no (client_id partition, primary_id, vendor_format order of client_id primary_id, vendor_format, vendor_number, vendor_number)

    from raj_table by sl_no asc

    SL_NO raj_id raj_number raj_format primary_id

    1                   1                   raj              rajvendor                 1

    1                   2                  raj              rajvendor                 1

    2                   3                   raj              rajvendor1                2

    2                   4                   raj              rajvendor1                2

    2                   5                  raj               rajvendor1                2

    3                   6                    raj              rajvendor2                3

    I need help with a SQL query to get the result as above without using the group by clause. I want to bring together the combination of separate line of the three columns (raj_id, raj_number, raj_format) and add a unique serial number for each online game (SL_NO column below). So, above there are 3 unique set of (raj_id, raj_number, raj_format) I can get in a group by clause, but I can not add prmiary_id, SL_NO values if I group by clause. I used the analytical functions like row_number() but no luck. Need solution for this.

    with t as)

    Select 'raj' raj_id, 'rajvend' raj_number, 1 raj_format, 1 primary_id Union double all the

    Select option 2, 'raj', 'rajvend', 1 double Union all

    Select 3, 'raj', 'rajvendor1', 2 double Union all

    Select 4, 'raj', 'rajvendor1', 2 double Union all

    Select 5, 'raj', 'rajvendor1', 2 double Union all

    Select 6, 'raj', 'rajvendor2', 3 double

    )

    Select dense_rank() over (order of raj_id, raj_number, raj_format) sl_no,

    t.*

    t

    order by primary_id

    /

    PRIMARY_ID RAJ RAJ_NUMBER RAJ_FORMAT SL_NO
    ---------- ---------- --- ---------- ----------
    1 1 raj rajvend 1
    1 2 raj rajvend 1
    2 3 raj rajvendor1 2
    2 4 raj rajvendor1 2
    2 5 raj rajvendor1 2
    3 6 raj rajvendor2 3

    6 selected lines.

    SQL >

    SY.

  • What is the best way to optimize a SQL query: call a function or doing a join?

    Hi, I want to know what is the best way to optimize a SQL query, call a function inside the SELECT statement, or make a simple join?

    It depends on.  Could be a.  Could be the other.  Could be no difference.  You would need to compare with your tables in your environment with your settings.

    If you put a gun to my head, I was given no other information and required that I answered the question, I would tend to wait that the join would be more effective.  In general, if you can do something in pure SQL, it will be more effective than if you call PL/SQL.

    Justin

  • Need help to write a SQL query complex

    I have the source tabe as below

    -> SOURCE_TABLE
    NAME     CUST_ID     SVC_ST_DT     SVC_END_DT 
    TOM        1               31/08/2009      23/03/2011 
    DOCK       2               01/01/2004      31/05/2010 
    HARRY      3               28/02/2007      31/12/2009 
    I want to load as target table below
    -> TARGET_TABLE
    NAME     CUST_ID                     SVC_ST_DT      SVC_END_DT 
    TOM      1           31/08/2009      31/12/2009 
    TOM      1           01/01/2010      31/12/2010 
    TOM      1           01/01/2011      23/03/2011 
    DOCK      2           01/01/2004      31/12/2004 
    DOCK      2           01/01/2005      31/12/2005 
    DOCK      2           01/01/2006      31/12/2006 
    DOCK      2           01/01/2007      31/12/2007 
    DOCK      2           01/01/2008      31/12/2008 
    DOCK      2           01/01/2009      31/12/2009 
    DOCK      2           01/01/2010      31/05/2010 
    HARRY      3           28/02/2007      31/12/2007 
    HARRY      3           01/01/2008      31/12/2008 
    HARRY      3           01/01/2009      31/12/2009 
    Is it possible to write a SQL query that returns the data in the same way above the target table.

    Published by: AChatterjee on April 30, 2012 07:14

    Published by: AChatterjee on April 30, 2012 07:14

    Or like this...

    SQL> ed
    Wrote file afiedt.buf
    
      1  with t as (select 'TOM' as NAME, 1 as CUST_ID, date '2009-08-31' as SVC_ST_DT, date '2011-03-23' as SVC_END_DT from dual union all
      2             select 'DOCK', 2, date '2004-01-01', date '2010-05-31' from dual union all
      3             select 'HARRY', 3, date '2007-02-28', date '2009-12-31' from dual)
      4  --
      5  -- end of test data
      6  --
      7  select name, cust_id, svc_st_dt, svc_end_dt
      8  from (
      9        select name
     10              ,cust_id
     11              ,greatest(svc_st_dt, add_months(trunc(svc_st_dt,'YYYY'),yr*12)) as svc_st_dt
     12              ,least(svc_end_dt, add_months(trunc(svc_st_dt,'YYYY'),(yr+1)*12)-1) as svc_end_dt
     13        from t
     14             cross join (select rownum-1 as yr
     15                         from   dual
     16                         connect by rownum <= (select extract(year from max(svc_end_dt)) - extract(year from min(svc_st_dt)) + 1 from t)
     17                        )
     18       )
     19  where svc_st_dt <= svc_end_dt
     20* order by 2, 3
    SQL> /
    
    NAME     CUST_ID SVC_ST_DT            SVC_END_DT
    ----- ---------- -------------------- --------------------
    TOM            1 31-AUG-2009 00:00:00 31-DEC-2009 00:00:00
    TOM            1 01-JAN-2010 00:00:00 31-DEC-2010 00:00:00
    TOM            1 01-JAN-2011 00:00:00 23-MAR-2011 00:00:00
    DOCK           2 01-JAN-2004 00:00:00 31-DEC-2004 00:00:00
    DOCK           2 01-JAN-2005 00:00:00 31-DEC-2005 00:00:00
    DOCK           2 01-JAN-2006 00:00:00 31-DEC-2006 00:00:00
    DOCK           2 01-JAN-2007 00:00:00 31-DEC-2007 00:00:00
    DOCK           2 01-JAN-2008 00:00:00 31-DEC-2008 00:00:00
    DOCK           2 01-JAN-2009 00:00:00 31-DEC-2009 00:00:00
    DOCK           2 01-JAN-2010 00:00:00 31-MAY-2010 00:00:00
    HARRY          3 28-FEB-2007 00:00:00 31-DEC-2007 00:00:00
    HARRY          3 01-JAN-2008 00:00:00 31-DEC-2008 00:00:00
    HARRY          3 01-JAN-2009 00:00:00 31-DEC-2009 00:00:00
    
    13 rows selected.
    
  • Case Based Condition of inner join in SQL query

    Hi Experts,
    CREATE TABLE PRODUCT_PRICE(PRODUCT_ID INTEGER,PRICE FLOAT);
    INSERT INTO PRODUCT_PRICE VALUES(1,1);
    INSERT INTO PRODUCT_PRICE VALUES(2,2);
    INSERT INTO PRODUCT_PRICE VALUES(3,1);
    INSERT INTO PRODUCT_PRICE VALUES(4,1);
    INSERT INTO PRODUCT_PRICE VALUES(5,3);
    INSERT INTO PRODUCT_PRICE VALUES(0,4);
    CREATE TABLE PRODUCT_TABLE (PRODUCTID INTEGER,OTHERID INTEGER);
    INSERT INTO PRODUCT_TABLE VALUES (1,0);
    INSERT INTO PRODUCT_TABLE VALUES (2,0);
    INSERT INTO PRODUCT_TABLE VALUES (3,1);
    INSERT INTO PRODUCT_TABLE VALUES (4,1);
    INSERT INTO PRODUCT_TABLE VALUES (5,2);
    I need to match the product_id = 0 to get the price of the product when there is othersid in the product table (otherid > 0). For this I created the query below.
    SELECT 
        PRODUCT_ID,
        PRICE 
    FROM 
        PRODUCT_TABLE
        INNER JOIN PRODUCT_PRICE ON PRODUCT_ID=PRODUCTID
    WHERE
        OTHERID=0
    UNION ALL
    SELECT 
        PRODUCT_ID,
        PRICE 
    FROM 
        PRODUCT_TABLE
        INNER JOIN PRODUCT_PRICE ON PRODUCT_ID=0
    WHERE
        OTHERID>0;
    My Question is, is that any way the SQLQuery above can be simplified in CASES and INTERNAL CONDITION JOIN in a single SQL QUERY?

    I can work around something like that,
    SELECT 
        PRODUCT_ID,
        PRICE 
    FROM 
        PRODUCT_TABLE
        INNER JOIN PRODUCT_PRICE ON * CASE WHEN OTHERID>0 THEN PRODUCT_ID=0 ELSE PRODUCT_ID=PRODUCTID END*
    Thank you
    SELECT CASE WHEN PT.OTHERID = 0 THEN PT.PRODUCTID ELSE 0 END AS PRODUCT_ID, PP.PRICE
      FROM PRODUCT_TABLE PT,  PRODUCT_PRICE PP
        WHERE CASE WHEN PT.OTHERID =0 THEN PT.PRODUCTID ELSE 0 END = PP.PRODUCT_ID
    

    Should it?

  • Help me with SQL Query to retrieve data from a view

    Hello Guru,

    I need help in my sql query.
    I use SQL TeraData.
    I want an Oracle result in the following form-

    Open tickets
    Open months failure / Repair Service s/o improvement request Total general
    2009-01-2 4 4 5 15
    2009-02 1 0 2 3 6
    2009-03 4 1 2 2 9
    Grand Total 7 5 8 10 30


    I wrote the query as where - TIME_PERIOD, RQST_TYPE_DM and DEMAND_SUMMARY_FCT are the points of view and I extract the data from the views only.

    Select NVL (CA. TIME_PERIOD. PERIOD_CD, 'Total') THAT year.
    COUNT (CASE WHEN CA. RQST_TYPE_DM. RQSTTYP_DESC Like '% of Break' THEN 1 END) as BreakFix
    COUNT (CASE WHEN CA. RQST_TYPE_DM. RQSTTYP_DESC as 'N/a', 1 END) by n/a
    COUNT (CASE WHEN CA. RQST_TYPE_DM. RQSTTYP_DESC as 'Improvement' THEN 1 END) accessories
    COUNT (CASE WHEN CA. RQST_TYPE_DM. RQSTTYP_DESC Like '% Service' THEN 1 END) as ServiceRequests
    COUNT (CA. RQST_TYPE_DM. RQSTTYP_DESC) AS grand_total
    FROM CA. TIME_PERIOD, CA. RQST_TYPE_DM, CA. DEMAND_SUMMARY_FCT
    WHERE (CA. DEMAND_SUMMARY_FCT. RQSTTYP_ID = CA. RQST_TYPE_DM. RQSTTYP_ID)
    AND (CASE
    WHEN CA. DEMAND_SUMMARY_FCT. MONTH_ID = CA. TIME_PERIOD. PERIOD_ID, 1
    WHEN {fn concat ({fn concat (SUBSTR (CA. TIME_PERIOD. {(PERIOD_CD, 3, 4),'-')}, SUBSTR (CA. TIME_PERIOD. PERIOD_CD, 7, 2))} BETWEEN ' 2009-01' AND ' 2009-03' THEN 1
    WHEN CA. DEMAND_SUMMARY_FCT. RQSTTYP_ID = '1' then 1
    END) = 1
    GROUP BY ROLLUP (CA. TIME_PERIOD. PERIOD_CD)

    After executing the query, I get the following error:
    3076: syntax Error: Data Type 'Time' does not match a defined Type name.
    :( Kindly help me with this and let me know where I'm wrong... Please.

    Messages indicates something wrong with your data... It would seem that the data does not match your format mask.

    Thus, the data or the format mask.

  • Need help with PL/SQL query complex

    I need help with a query that need access to data from 3 tables. That's what I did

    I created 3 tables

    CREATE TABLE post_table
    (
    post_id varchar (20),
    datepost DATE,
    KEY (post_id) elementary SCHOOL
    ) ;

    CREATE TABLE topic
    (
    TOPIC_ID varchar (20),
    name varchar (20),
    PRIMARY KEY (topic_id)
    );

    CREATE TABLE blogpost_table
    (
    TOPIC_ID varchar (20),
    post_id varchar (20),
    PRIMARY KEY (topic_id, post_id);
    FOREIGN KEY (topic_id) REFERENCES topic (topic_id) ON DELETE CASCADE,
    FOREIGN KEY (post_id) REFERENCES post_table (post_id) ON DELETE CASCADE
    );


    Now, I inserted a few values in these tables as

    INSERT INTO post_table VALUES ('p1', to_date ('2009-09-14 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p2', to_date ('2009-07-18 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p3', to_date ('2009-07-11 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p4', to_date ('2009-03-11 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p5', to_date ('2009-07-13 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p6', to_date ('2009-06-12 18:00 "," MM/DD/YYYY mi:ss'));))
    INSERT INTO post_table VALUES ('p7', to_date ('2009-07-11 18:00 "," MM/DD/YYYY mi:ss'));))

    INSERT INTO VALUES subject ("t1", "baseball");
    INSERT INTO category VALUES ('t2', 'football');

    INSERT INTO blogpost_table VALUES ("t1", "p1");
    INSERT INTO blogpost_table VALUES ('t1', 'p3');
    INSERT INTO blogpost_table VALUES ("t1", "p4");
    INSERT INTO blogpost_table VALUES ('t1', 'p5');
    INSERT INTO blogpost_table VALUES ('t2', 'p2');
    INSERT INTO blogpost_table VALUES ('t2', 'p6');
    INSERT INTO blogpost_table VALUES ("t2", "p7");


    I'm launching SQL queries on the table in this topic.

    I want to write a SQL query that returns me the name of a topic (s) and the number of blog_post (s) associated with the topic in descending order of the number of blog posts created in July.

    Can someone please help me to write this query?

    Thank you

    Published by: user11994430 on October 9, 2009 07:24

    Thanks for the test of the configuration!

    SQL>SELECT   t.NAME, COUNT(*)
      2      FROM topic t, blogpost_table b, post_table p
      3     WHERE b.topic_id = t.topic_id
      4       AND p.post_id = b.post_id
      5       AND p.datepost >= DATE '2009-07-01'
      6       AND p.datepost < DATE '2009-08-01'
      7  GROUP BY t.NAME
      8  ORDER BY COUNT(*) desc;
    
    NAME                   COUNT(*)
    -------------------- ----------
    baseball                      2
    soccer                        2
    

    HTH, Urs

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

  • Need help to reduce the cost of my sql Query below 100 to optimize.

    Can you please suggest how to reduce the COST of my SQL query? Is it possible to get the < 100 COST?

    My goal:
    ------------------------

    To recover the data of length (a column is in normalised_event: table) corresponding to each type of call (which is to extract the column rc.abbreviation in reference_code: table) in a given range of dates. So I wrote the following as SQL below:

    ------------------------------------------------------------------------------------------------------------------
    Select nvl (sum (round(ne.duration/60,3)), 0), rc.abbreviation
    Since the rc reference_code, normalised_event not
    where to_char (rc.reference_code) = ne.full_path
    and rc.reference_type_id = 505002 AND
    trunc (don't. CHARGE_START_DATE) between trunc (to_date (January 1, 2008 "," dd-mm-yyyy hh24:mi:ss'))))
    and trunc (to_date (January 1, 2009 "," dd-mm-yyyy hh24:mi:ss'))))
    Rc.abbreviation group

    -----------------------------------------------------------------------------------------------------------------

    IAM using Toad Software which is taken in charge by oracle 9i.


    Explain the plan above query is:

    explain plan
    Set statement_id = "mp01" for
    Select nvl (sum (round(ne.duration/60,3)), 0), rc.abbreviation
    Since the rc reference_code, normalised_event not
    where to_char (rc.reference_code) = ne.full_path
    and rc.reference_type_id = 505002 AND
    trunc (don't. CHARGE_START_DATE) between trunc (to_date (January 1, 2008 "," dd-mm-yyyy hh24:mi:ss'))))
    and trunc (to_date (January 1, 2009 "," dd-mm-yyyy hh24:mi:ss'))))
    Rc.abbreviation group



    Select LPad (' ', 2 *(Level-1)). Level | '.' || NVL (position 0). ' ' ||
    Operation | ' ' || Options of | ' ' || Object_name | ' ' ||
    Object_type | ' ' || Decode (id, 0, Statement_Id |) "Cost = ' | Position)
    "Query plan.
    From Plan_Table
    Start with id = 0 and Statement_Id = 'mp01 ".
    Connect Id Parent_Id = prior
    And Statement_Id = 'mp01 ";


    ---------------------------Query Plan explained is----------------------------------------------------------

    1.555 INSTRUCTION SELECT mp01 cost = 555
    2.1 TYPE GROUP
    3.1 FILTER
    4.1 HASH JOIN
    5.1 TABLE ACCESS BY INDEX ROWID REFERENCE_CODE
    6.1 INDEX RANGE SCAN NON-UNIQUE I_REFERENCE_CODE_REF_TYPE
    5.2 PARTITION RANGE ALL THE
    6.1 TABLE ACCESS FULL NORMALISED_EVENT

    -Automatic tracking of the SQl query is:.

    recursive calls - 0
    DB block gets - 0
    compatible gets - 174
    physical reads - 0
    size - 104
    Parse count (hard) - 0
    Parse count (chess) - 0
    run the County - 2
    bytes sent via SQL * Net to dblink - 0
    bytes received via SQL * Net from dblink - 0

    I was wrong. Once again, this shows how it is dangerous to assume (I assumed that FBI was new in 10g because it is when I used them), and the power of the community to ensure that accurate information is provided.

    John

Maybe you are looking for

  • F7 key does not work on my Equium M50-244

    Hi, first time here so I hope that someone can help meMy son spilled some water on my keyboard and some keys don't work. One being my F7 key I need to be able to shed some light on my monitor.Does anyone know another way to do this. Concerning

  • project style instrument driver

    Hi all 1. What is the advantage or the importance of the project-style Instrument pilot pilot instrument type LLB? 2. in the event that the project file be located in the directory "C:\Program NIUninstaller Instruments\LabVIEW 8.0\instr.lib"? (My pro

  • Silverlite with NetFlix shows black screen

    Have a black screen when trying to watch a Netflix movie - have reinstalled Silverlite - no help - case # 1179561443

  • When printing envelopes paper jams

    Hello When I try to print multiple envelopes, the following message appears: "short paper. I have a lot 4 1/8 x 9 1/2 envelopes that will print perfectly - if I hit 'print' every time. I tried to expand margins in the preview, and I still had no luck

  • r007tx: defection of brightness screen

    My laptop screen brightness is defecting, is sometimes increase and some it diminishes over time to not charge. When I want to play a vedio on the increase and after closeing it shortly after it decreases, but the amount of the increase or decrease i