Help with joins

Hi,
I am not sure if I am doing something wrong here, but would appreciate if someone point out my mistake.
I have two table item and item_status
item_status do not contain all the items but only the ones which have specific status
Question(1):
select count(*) from item
and
select count(*) from item left join item_status on item.itemid = item_status.item_id
Result of these two queries dont match. Can you'll plz help me understand it.
Question(2):
I want count of items from table item by location (location is another field in table item) but I want to exclude items which have status lost in the item_status table.
This is the query I used:
select location, count(*) from item left join item_status on item.itemid = item_status.item_id where item_status.status = 'lost'
is this the correct way, coz when I tried the figures where way to low,
Thanks,
Raja

Hi, Raja,
Raja Gopalan wrote:
Hi,
I am not sure if I am doing something wrong here, but would appreciate if someone point out my mistake.
I have two table item and item_status
item_status do not contain all the items but only the ones which have specific status
Question(1):
select count(*) from item
and
select count(*) from item left join item_status on item.itemid = item_status.item_id
Result of these two queries dont match. Can you'll plz help me understand it.If there can be many rows in item_status that all match the same row in item, then the 2nd query will have a higher COUNT than the first.
If you'd post your tables, I could show you in detail.
Since you didn't I'll use tables from the scott schema.
SELECT  d.deptno
FROM     scott.dept     d;produces 4 rows:
.   DEPTNO
        10
        20
        30
        40Only 3 of these rows have a match in the mep table, but the ones that match have many matches.
SELECT     d.deptno
,     e.ename
FROM          scott.dept     d
LEFT OUTER JOIN     scott.emp     e     ON     d.deptno     = e.deptno;produces 15 rows
.   DEPTNO ENAME
        20 SMITH
        30 ALLEN
        30 WARD
        20 JONES
        30 MARTIN
        30 BLAKE
        10 CLARK
        20 SCOTT
        10 KING
        30 TURNER
        20 ADAMS
        30 JAMES
        20 FORD
        10 MILLER
        401 row for each row in emp that has a match in dept (that is all 14 rows in emp) plus 1 row for every row in dept that does not have a match in emp (1 row).
Question(2):
I want count of items from table item by location (location is another field in table item) but I want to exclude items which have status lost in the item_status table.
This is the query I used:
select location, count(*) from item left join item_status on item.itemid = item_status.item_id where item_status.status = 'lost'
is this the correct way, coz when I tried the figures where way to low,If you want a count by location, then you should say "GROUP BY location".
You probably need a sub-query to check for 'lost'. Without seeing your tables and data, I can't be sure.
Maybe something like
SELECT  location
,     COUNT (*)
FROM     item
WHERE     itemid     NOT IN     (     -- Begin subquery to find bad item_ids
                   SELECT  item_id
               FROM     item_status
               WHERE     status     = 'lost'
                   )     -- End subquery to find bad item_ids
GROUP BY  location
;

Similar Messages

  • Newbie: help with join in a select query

    Hi: I need some help with creating a select statement.
    I have two tables t1 (fields: id, time, cost, t2id) and t2 (fields: id, time, cost). t2id from t1 is the primary key in t2. I want a single select statement to list all time and cost from both t1 and t2. I think I need to use join but can't seem to figure it out even after going through some tutorials.
    Thanks in advance.
    Ray

    t1 has following records
    pkid, time, cost,product
    1,123456,34,801
    2,123457,20,802
    3,345678,40,801
    t2 has the following records
    id,productid,time,cost
    1,801,4356789,12
    2,801,4356790,1
    3,802,9845679,100
    4,801,9345614,12
    I want a query that will print following from t1 (time and cost for records that have product=801)
    123456,34
    345678,40
    followed by following from t2 (time and cost for records that have productid=801)
    4356789,12
    4356790,1
    9345614,12
    Is this possible?
    Thanks
    ray

  • Help with Joining a few tables

    I need a help using JOINS. I plan to create ONE VIEW by bringing in all fields from First and Second table and a few chosen columns from Third, Fourth and Fifth tables. I have put to together below select statement which appears to be working syntax-wise but not efficient and may have dupes.
    Table1 - RPT_APRL_PRODUCT with key field KEY_MATERIAL (KEY_MATERIAL = DIVISION||PLAN_CTRY||MKT_TYP_ID||MATERIAL)
    Table 2 - RPT_FWEQ_PRODUCT with key field KEY_MATERIAL (KEY_MATERIAL = DIVISION||PLAN_CTRY||MATERIAL)
    Table 3 - NSC_PROD_CIMG has a Key Field = MATERIAL_NBR
    Table 4- STAGE#EMEA_NSAP.NSC_PROD_REG_CIMG has the Key field MATERIAL_NBR, REG_ID
    Table 5 - STAGE#EMEA_NSAP.NSC_PROD_REG_CYC_CIMG has Key Fields MATERIAL_NBR, REG_ID, CYC_ID and ORGVERSIONID
    Columns needed from Table 3 -- B.DIVISION, B.DIVISIONNAME, B.SUBLABEL, B.SUBLABELNAME and B.DEVELOPMENTREGION.
    Columns needed from Table 4 --- C.GLOBALSOURCEINDICATOR
    Columns needed from Table 5--- D.CARRYOVERFLAG
    SELECT statement:
    SELECT /*+ parallel (a,5) parallel (NET,5) */
    a.key_material,
    a.mkt_typ_id,
    a.region_id,
    CASE
    WHEN a.region_id = '3' THEN 'USA'
    WHEN a.region_id = '4' THEN 'EMEA'
    WHEN a.region_id = '7' THEN 'CANADA'
    END AS region_desc,
    a.mkt_reg_cd,
    CASE
    WHEN a.mkt_reg_cd = '01' THEN 'USA'
    WHEN a.mkt_reg_cd = '02' THEN 'EMEA'
    WHEN a.mkt_reg_cd = '05' THEN 'AMER'
    END AS mkt_reg_desc,
    a.cat_bus_cd1,
    a.cat_bus_desc1,
    a.cat_bus_cd2,
    a.cat_bus_desc2,
    a.cat_bus_cd3,
    a.cat_bus_desc3,
    a.cat_bus_cd4,
    a.cat_bus_desc4,
    a.mkstr_cd,
    a.mkt_clsfn_desc,
    a.mkt_clsfn_cd1,
    a.mkt_clsfn1_desc,
    a.mkt_clsfn_cd2,
    a.mkt_clsfn2_desc,
    a.mkt_clsfn_cd3,
    a.mkt_clsfn3_desc,
    a.exp_sty_ind,
    a.silh_cd,
    a.silh_desc,
    a.whlsl_prc,
    0,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    a.gender_age_class_id,
    a.gender_age_desc,
    a.sports_activity_class_id,
    a.sports_act_cls_desc,
    a.gblcatsummcode,
    a.gblcatsummdesc,
    a.gblcatcorefocuscode,
    a.gblcatcorefocusdesc,
    a.segment,
    a.segmentname,
    a.l4l_fl,
    NET.DIVISION,
    NET.DIVISIONNAME,
    NET.SUBLABEL,
    NET.SUBLABELNAME,
    NET.DEVELOPMENTREGION,
    NULL,
    NULL,
    NULL,
    NET.globalsourceindicator,
    NET.CARRYOVERFLAG,
    a.zz_chng_tmst,
    a.zz_update_tmst,
    a.zz_insert_tmst
    FROM RPT_APRL_PRODUCT A,
    (SELECT
    APRL.DIVISION||APRL.PLAN_CTRY||APRL.MKT_TYP_ID||APRL.MATERIAL ; AS KEY_MATERIAL,
    B.DIVISION,
    B.DIVISIONNAME,
    B.SUBLABEL,
    B.SUBLABELNAME,
    B.DEVELOPMENTREGION,
    C.GLOBALSOURCEINDICATOR,
    D.CARRYOVERFLAG
    from RPT_APRL_PRODUCTAPRL,
    NSC_PROD_CIMG B,
    NSC_PROD_REG_CIMG C,
    NSC_PROD_REG_CYC_CIMG D
    where APRL.MATERIAL = B.MATERIAL_NBR AND
    APRL.MATERIAL = C.MATERIAL_NBR AND
    APRL.MATERIAL = D.MATERIAL_NBR AND
    C.REG_ID = D.REG_ID) NET
    WHERE A.KEY_MATERIAL = NET.KEY_MATERIAL(+)
    Thanks for help in advance.

    I have 4 tables and these are some sample data for
    RPT_APRL_PRODUCT - Key Field = KEY_MATERIAL (this is a combination of plan_ctry,division,mkt_typ_id and material)
    Sample data
    KEY_MATERIAL          PLAN_CTRY   DIVISION  MKT_TYP_ID              MATERIAL
    10PART1136353-010      PART          10              1                      136353-010
    10AMER1136353-010      AMER          10              1                      136353-010
    10USA1136353-010       USA           10              1                      136353-010
    10CANA1136353-010      CANA          10              1                      136353-010
    10PART1137508-050      PART          10              1                      137508-050
    10AMER1137508-050      AMER          10              1                      137508-050
    10CANA1137508-050      CANA          10              1                      137508-050
    10USA1137508-050       USA           10              1                      137508-050
    10PART1137617-050      PART          10              1                      137617-050
    10AMER1137617-050      AMER          10              1                       137617-050nsc_prod_reg_cimg - keys (material_nbr and reg_id)
    MATERIAL                REG_ID          GLOBALSOURCEINDICATOR
    136353-010      3                                     G
    136353-010      6                                     G
    136353-010      7                                    
    137508-050      3                                    
    137508-050      6                                     G
    137508-050      7                                    
    137508-050      46                                    G
    137617-050      3                                    
    137617-050      6                                    
    137617-050      46                                    nsc_prod_reg_cyc_cimg - key is material_nbr, cyc_id, reg_id and orgversion_id
    MATERIAL_NBR       CYC_ID                    orgversion_id                                reg_ID                CARRYOVERFLAG
    136353-010      101                             1                                          3                             Y       
    136353-010      101                              1                                          6                             Y      
    136353-010      101                               1                                          7                             N      
    137508-050      202                               1                                          3                             Y     
    137508-050      202                               1                                          6                             N       
    137508-050      202                               1                                          7                                    
    137617-050      205                               1                                          3                                    
    137617-050      205                               1                                          6                                    
    185204-402      181                              1                                          8                                    
    185204-402      182                               1                                          8                                     nsc_prod_cimg - key is material_nbr
    MATERIAL_NBR     SUBLABEL     SUBLABELNAME
    136353-010           
    137508-050                GD           Good
    137617-050
    185204-402
    185204-402
    185204-402                BE            Better
    185204-402
    185204-402
    185204-402               CO            Core
    185204-402               BS             BestWhat I intend to do, is to create one view by joining these four tables. The columns key_material, plan_ctry, division and MKT_TYP_ID come from RPT_APRL_PRODUCT. I need to join these tables in such a way that I bring in the other 1 or 2 columns each from the 3 tables as described above. The result should have a unique key_material and have the other column data in the view as well.
    Result should be all the columns described above, something like this below...
    KEY_MATERIAL          PLAN_CTRY   DIVISION  MKT_TYP_ID              MATERIAL      SUBLABELNAME  CARRYover_FL
    10PART1136353-010      PART          10              1                      136353-010
    10AMER1136353-010      AMER          10              1                      136353-010

  • Airport express vista:help with joining a protected or unprotected network

    hello,
    i've been trying to set up a network between my computer and the airport express, with no luck,
    it works if i don't tell it to join my networks, but then i don't have internet access,
    and when i'm connected to the internet, i can't get both of them to work,
    any suggestions?
    i just need the airport for music, not internet, but apparently, two routers can't use one wi-fi card, so that's why it needs to join an existing network, that's what i understood from the different posts,
    i have unsecured, and secured connections available,(the unsecured network is faster so i'd like to use that one)
    PS: i noticed that the airport used the ETHERNET mac address, don't know if that helps,
    thank you in advance,
    i'm running out of ideas,
    Nay

    Perform a "hard" reset of the AX
    - (ref: http://docs.info.apple.com/article.html?artnum=108044)
    Setup the AX
    Connect your computer directly (using an Ethernet cable) to the Ethernet port of the AX, and then, using the AirPort Admin Utility check these settings:
    AirPort tab
    - Base Station Name: <whatever you wish or use the default>
    - AirPort Network Name: <whatever you wish or use the default>
    - Create a closed network (unchecked)
    - Wireless Security: Not enabled
    - Channel: Automatic
    - Mode: 802.11b/g Compatible
    Internet tab
    - Connect Using: Ethernet
    - Configure: Manually
    - IP address: <provided by your university>
    - Subnet mask: <provided by your university>
    - Router address: <provided by your university>
    - DNS servers: <provided by your university>
    - WAN Ethernet Port: Automatic
    Network tab
    - Distribute IP addresses (unchecked)

  • Help with Joining two SharePoint lists using LINQ

    Hi Guys,
    I have found many threads with this question. Although I had one doubt. I wanted to know that while performing a Join operation on two SharePoint Lists using LINQ does the column on which we are performing the join operation need to be a Lookup column?
    I was initially using CAML but since my lists does not contain lookup columns I switched to LINQ but my doubt still remains.
    I would really appreciate any help from you guys and also would appreciate if I could get some examples that I could refer to.
    Thank you

    Joins in LINQ to SharePoint 2010
    How to: Query Using LINQ to SharePoint
    This post is my own opinion and does not necessarily reflect the opinion or view of Slalom.

  • Need help with join

    Extract each entry from BSEG for BELNRs in BKPF-BELNR,
    and KOSTL in ZTABLE-KOSTL.
    sum(DMBTR) by KOSTL into
    internal tab <ITAB (fields KOSTL, DMBTR)>.
    i wrote the code like this:
    Select sum( aDMBTR ) aKOSTL into inkostltotal from BSEG as a
    inner join BKPF as b on bBELNR = aBELNR
    inner join Ztable as c on c~KOSTL = a-KOSTL
    group by a~KOSTL.
    it was giving error:
    You cannot use comparisons with column column references in pool and
    cluster tables: "A~BELNR". column references in pool and cluster
    tables: "A~BELNR". column references in pool and cluster tables:
    "ABELNR". column tables: "ABELNR".
    i need to use select, sum, group by to solve this can some one
    help me with this.

    hi saritha,
                   y ur not using for all entries, that will best in this situation.
    use for all entries like that
    CLEAR : T_EQUZ,T_EQUZ[].
    SELECT * FROM EQUZ INTO TABLE T_EQUZ
                       WHERE DATBI = '99991231'.
    IF NOT T_EQUZ[] IS INITIAL.
      select J_3GBELNRI equnr J_3GEMPFAE into
           corresponding fields of table
           T_J_3GBELP from J_3GBELP
           FOR ALL ENTRIES IN T_EQUZ
           where j_3guposnr ne '1'
           and J_3GEMPFAE in Reciver
           and equnr = T_EQUZ-EQUNR.
    regards
    vijay dwivedi
    rewards if usefull

  • Help with join query

    Hi,
    I was wondering if someone could help me out with a join question
    I have threetables, phase, project and projectPhase. Primary keys in bold, foreign in italiz, foreign and primary in bold.italic:
    project
    projectCode
    phase
    phaseCode
    projectPhase
    projectCode
    phaseCode
    I was wondering is there a way to query to see, for a given project code, what phases that project has not got information for? I think I need an outer join for this but I'm not sure
    Thanks!

    i agree with you Jens thanks for spotting that i might have overlooked.
    try using Jens solution and it produce the result that you want. all you had to do is if the values are in different upper and lower case wrap it with either UPPER or LOWER function.
    SQL> select * from project;
    PROJECTCOD
    NNUU
    MKKU
    SQL> select * from phase;
    PHASECODE
    Req
    Des
    Plan
    SQL> select * from projectphase;
    PROJECTCOD PHASECODE
    NNUU       REQ
    NNUU       Des
    SQL> select Upper(phaseCode) phaseCode
      2    from phase
      3   minus
      4  select Upper(phaseCode) phaseCode
      5    from projectPhase
      6   where projectcode= 'NNUU';
    PHASECODE
    PLAN
    SQL>

  • Help with Joins in ABAP

    Hello Experts,
    I am struggling with a problem.
    In my development I have two db tables for eg. Table A and Table B.
    Now table A has about 200,000 entries and table B has about 800,000 entries.
    I want to delete all the extra entries (junk entries-not  present in A but present in B) from table B on the basis of one field that is common between them
    i.e. All the entries for whom 'A-field NE B-field'
    Now i tried using internal tables but the loop execution is taking forever.
    And I tried using a Select query for all entries:
    SELECT *
        FROM B
          INTO TABLE itab_B
          FOR ALL ENTRIES IN itab_A
    WHERE field EQ itab_A-field.
    This query gives me the records which are present in both tables.
    But if I try to change the 'where' condition to 'NE' it does not work.
    Is there any join statement to meet my requirement?
    Thanks in Advance
    Omkar

    Hi Omkar,
    reduce the internal table to the fields you really need to identify, the key fields and the fields of interest. Use field-symbols for loops. make one of the two tables a hashed table with unique key.
    You will observe a performance enhancement of factor 100 at least.
    If you had given more information or even a piece of code, I may have done the coding for you.
    Regards,
    Clemens

  • Help with joining one table to several

    I have the following table
    MSELECT
    Res_ID
    Res_type
    34
    501
    56
    501
    72
    501
    81
    502
    90
    502
    100
    502
    47
    503
    48
    503
    The RES_ID will link to different tables such as tablea, tableb or tablec based on the RES_Type value .g. RES_Type ID 501 will link to tableA and 502 will link to TableB and 503 will link to TableC.
    I have created the following query:
    Select * from MSSELECT MSEL
    Inner join tablea  ta on
    Ta.id = MSEL.ID and
    Res_type = 501
    Inner join tableb tb on
    Tb.id = MSEL.ID and
    Res_type = 501
    If I run the following query then results are returned.
     Select * from MSSELECT MSEL
    Inner join tablea  ta on
    Ta.id = MSEL.ID and
    Res_type = 501
    However if I run the following query it is returning no results:
    Select * from MSSELECT MSEL
    Inner join tablea  ta on
    Ta.id = MSEL.ID and
    Res_type = 501
    Inner join tableb tb on
    Tb.id = MSEL.ID and
    Res_type = 501

    Try:
    Select * from MSSELECT MSEL
    LEFT OUTER join tablea  ta on
    Ta.id = MSEL.ID and
    Res_type = 501
    LEFT OUTER  join tableb tb on
    Tb.id = MSEL.ID and
    Res_type = 501
    Best Wishes, Arbi; Please vote if you find this posting was helpful or Mark it as answered.

  • Help with joining tables

    hello can some one help me in joining the tables
    po_vendors of AP and gl_je_headers or gl_he_headers of GL
    thankyou

    How about this:
    Build first an auxiliary table (you can truncate it every time) and in it:
    create table auxtab as
    select distinct employeeid, row_date from table1
    union
    select distinct employeeid, row_date from table2
    union
    select distinct employeeid, row_date from table3
    union
    Then you can use this "auxiliar" table as the driving one for outer joins
    select * from auxtab left outer join table1 on ()
    left outer join table2 on ()
    left outer join table3 on ()
    etc..

  • Help with Join

    All,
    How to join inv.mtl_category_sets_tl and ibe.msites_b. I am having trouble to find which tables i need to join these two tables
    I am not getting right mini site id for the caterogy set name
    Your help is highly appreciated
    Regards
    Edited by: 792011 on Sep 12, 2011 12:49 PM

    792011 wrote:
    Hi Bravid,
    11110 is the site_id for ABC Catalog and same thing for 11111 DEF Catalog. These two are different websites
    RegardsOkay so why do you have an entry for 11110 DEF and an entry for 11111 ABC in your source data? Where in your source data is there anything that identifies 11110 as site ABC - i.e. is there another attribute here or are you just planning to hard code it?
    David

  • Help with joining AP to WLC 5508 Getting error in LOG's

    I am tryign to join my first AP to the 5508 and am gettign this error int he logs.
    *Dec 07 10:42:31.067: %DTL-3-NPUARP_ADD_FAILED: dtl_arp.c:2280 Unable to add an ARP entry for 0:0.0.0 to the network processor. entry does not exist
    The management Interface is on the the same vlan as the AP , both untagged ports. the AP gets an ip address from my dhcp server.
    Any ideas?
    Thanks

    AIR-CAP3502I-A-K9
    Also here's this if useful
    Discovery phase statistics
    - Discovery requests received.............................. 114
    - Successful discovery responses sent...................... 0
    - Unsuccessful discovery request processing................ 0
    - Reason for last unsuccessful discovery attempt........... Not applicable
    - Time at last successful discovery attempt................ Not applicable
    - Time at last unsuccessful discovery attempt.............. Not applicable
    Join phase statistics
    - Join requests received................................... 0
    - Successful join responses sent........................... 0
    - Unsuccessful join request processing..................... 0
    - Reason for last unsuccessful join attempt................ Not applicable
    - Time at last successful join attempt..................... Not applicable
    - Time at last unsuccessful join attempt................... Not applicable
    Configuration phase statistics
    - Configuration requests received.......................... 0
    - Successful configuration responses sent.................. 0
    - Unsuccessful configuration request processing............ 0
    - Reason for last unsuccessful configuration attempt....... Not applicable
    --More-- or (q)uit
    - Time at last successful configuration attempt............ Not applicable
    - Time at last unsuccessful configuration attempt.......... Not applicable
    Last AP message decryption failure details
    - Reason for last message decryption failure............... Not applicable
    Last AP disconnect details
    - Reason for last AP connection failure.................... Not applicable
    Last join error summary
    - Type of error that occurred last......................... None
    - Reason for error that occurred last...................... Not applicable
    - Time at which the last join error occurred............... Not applicable
    Ethernet Mac : 00:00:00:00:00:00  Ip Address : 192.168.14.50

  • Help with joining two queries

    Hi
    We recently inherited a database and we are re-wrting some queries. The first is
    SELECT gu.GEOGRAPHIC_UNIT_ID, gu.GEOGRAPHIC_UNIT_DESC, aggDataC.DATA as Capacity, aggDataP.DATA as Production
    FROM GEOGRAPHIC_UNIT_RELATIONSHIP gur, GEOGRAPHIC_UNIT
    gu, AGGREGATED_DATA aggDataC, AGGREGATED_DATA aggDataP
    WHERE      gur.PARENT_GEOGRAPHIC_UNIT_ID = :geographicUnitId AND gur.CHILD_GEOGRAPHIC_UNIT_ID = gu.GEOGRAPHIC_UNIT_ID
    AND aggDataC.GEOGRAPHIC_UNIT_ID = gu.GEOGRAPHIC_UNIT_ID
    AND ((:CommodityGroupId IS NULL AND
    aggDataC.COMMODITY_GROUP_ID IS NULL) OR (:CommodityGroupId = aggDataC.COMMODITY_GROUP_ID))
    AND ((:CommodityTypeId IS NULL AND
    aggDataC.COMMODITY_TYPE_ID IS NULL) OR (:CommodityTypeId = aggDataC.COMMODITY_TYPE_ID))
    AND ((:PlantTypeId IS NULL AND aggDataC.PLANT_TYPE_ID
    IS NULL) OR (:PlantTypeId = aggDataC.PLANT_TYPE_ID))
    AND aggDataC.ORGANISATION_ID is NULL
    AND aggDataC.YEAR = :Year
    AND aggDataC.STAT_TYPE_ID = (SELECT stat_type_id FROM
    stat_type WHERE stat_type = 'CAP')
    AND aggDataC.STAT_PERIOD_TYPE_ID = :StatPeriodTypeId
    AND aggDataP.GEOGRAPHIC_UNIT_ID = gu.GEOGRAPHIC_UNIT_ID
    AND ((:CommodityGroupId IS NULL AND
    aggDataP.COMMODITY_GROUP_ID IS NULL) OR (:CommodityGroupId = aggDataP.COMMODITY_GROUP_ID))
    AND ((:CommodityTypeId IS NULL AND
    aggDataP.COMMODITY_TYPE_ID IS NULL) OR (:CommodityTypeId = aggDataP.COMMODITY_TYPE_ID))
    AND ((:PlantTypeId IS NULL AND aggDataP.PLANT_TYPE_ID
    IS NULL) OR (:PlantTypeId = aggDataP.PLANT_TYPE_ID))
    AND aggDataP.ORGANISATION_ID is NULL
    AND aggDataP.YEAR = :Year
    AND aggDataP.STAT_TYPE_ID = (SELECT stat_type_id FROM
    stat_type WHERE stat_type = 'PRD')
    The above query returns only the geographic units that have capacity and production figures.
    I want to return all other regions that have a plantypeid regardless of whether they have capacity and production data.
    I tried to use outer joins but this has not worked. The database is an oracledatabase
    the below query returns all the geographic regions I need
    SELECT gu.GEOGRAPHIC_UNIT_ID, gu.GEOGRAPHIC_UNIT_DESC
    FROM GEOGRAPHIC_UNIT_RELATIONSHIP gur, GEOGRAPHIC_UNIT gu
    where
    gur.PARENT_GEOGRAPHIC_UNIT_ID = :geographicUnitId
    AND gur.CHILD_GEOGRAPHIC_UNIT_ID = gu.GEOGRAPHIC_UNIT_ID
    ANy idea how I merge the 2 queries?

    UNION

  • Help with WITH clause

    I have a complicated summary report that I am trying to put together. Using the WITH clause is substantially reducing the query time. Here's what I have (it works):
    with ldsntons as
    (select c.DATE_INDEX, j.FACTORY_ID, s.SHORT_NM||' ('||j.STATION_ID||') '||j.PILE_CODE_ALT_FLAG as STN_NM,
           COUNT(j.LOAD_JOB_ID) as LDS,
        CASE SUM(w.SPOT_WEIGHT)
           WHEN 0 THEN SUM(j.MAN_SPOT_WT)
           ELSE SUM(w.SPOT_WEIGHT)
         END TONS
      from TC c, TC_LOAD_JOBS j, SPOT_WEIGHTS w, STATIONS s
    where c.TC_ID = j.TC_ID
       and FN_STN_KEY(j.FACTORY_ID, j.STATION_ID) = s.KEY_ID
       and j.LOAD_RATE_ID = w.LOAD_RATE_ID
       and c.DATE_INDEX = w.DATE_INDEX
       and c.DATE_INDEX BETWEEN to_date(:P2053_DT,'MM/DD/YYYY') AND to_date(:P2053_DT,'MM/DD/YYYY') +15  -- Optional filter
    group by c.DATE_INDEX, j.FACTORY_ID, j.STATION_ID, s.SHORT_NM, j.PILE_CODE_ALT_FLAG)
    SELECT STN_NM as STN,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')    THEN LDS  END), 0) D01LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')    THEN TONS END), 0) D01TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+1  THEN LDS  END), 0) D02LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+1  THEN TONS END), 0) D02TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+2  THEN LDS  END), 0) D03LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+2  THEN TONS END), 0) D03TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+3  THEN LDS  END), 0) D04LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+3  THEN TONS END), 0) D04TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+4  THEN LDS  END), 0) D05LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+4  THEN TONS END), 0) D05TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+5  THEN LDS  END), 0) D06LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+5  THEN TONS END), 0) D06TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+6  THEN LDS  END), 0) D07LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+6  THEN TONS END), 0) D07TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+7  THEN LDS  END), 0) D08LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+7  THEN TONS END), 0) D08TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+8  THEN LDS  END), 0) D09LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+8  THEN TONS END), 0) D09TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+9  THEN LDS  END), 0) D10LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+9  THEN TONS END), 0) D10TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+10 THEN LDS  END), 0) D11LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+10 THEN TONS END), 0) D11TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+11 THEN LDS  END), 0) D12LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+11 THEN TONS END), 0) D12TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+12 THEN LDS  END), 0) D13LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+12 THEN TONS END), 0) D13TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+13 THEN LDS  END), 0) D14LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+13 THEN TONS END), 0) D14TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+14 THEN LDS  END), 0) D15LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+14 THEN TONS END), 0) D15TNS,
    SUM(LDS),
    SUM(TONS)
      FROM ldsntons
    WHERE FACTORY_ID = :P2053_ORG_ID
    GROUP BY STN_NMBasically the report lists a location with daily activity in columns for 15 days from that location. What I need to add are subtotals at the end of the line. I tried duplicating my WITH clause to pull the subtotals, but I kept getting an incorrect join that was listing all the amounts regardless of the date, which isn't correct.
    The other kicker is that I can get it to work fine if I restrict the initial WITH statement to include a WHERE clause (-- Optional filter) that filters it down to only data within the range, but the requestor wants to see all the locations regardless of whether they haul during the time period or not.
    Your help is greatly appreciated.

    This report is a cross-tab of data compiled from 4-5 other tables. I understand what you are asking, but I can't possibly post that much information. This is an aggregation of hundreds of employee timecards per day having dozens of loads; even to get a representative set you would need several hundred lines. The report lists the loads and tons for each of the 15 days on the report by virtue of the case statement. What I need is a sub-total (by line) of those 15 days into one field at the end of the line. It's not that hard to do in a spreadsheet, but we're trying to skip the need to export to csv and do manual manipulations after the fact.
    This is what I want the report to look like:
    STATION     DAY1LOADS   DAY1TONS   DAY2LOADS   DAY2TONS ...  DAY15LOADS   DAY15TONS   SUBTTLLOADS   SUBTTLTONS
    Ada            10           300          12        350             5         150       40        1200SUBTTLTONS = DAY1TONS + DAY2TONS + DAY3TONS, etc.
    I was hoping there was a simpler way of doing it than adding the individual columns into an aggregate. I can develop the query I need, I just need help with joining it in to the base query. This query gets me the subtotals:
    select s.SHORT_NM||' ('||j.STATION_ID||') '||j.PILE_CODE_ALT_FLAG as STN_NM,
           COUNT(j.LOAD_JOB_ID) as LDS,
        CASE SUM(w.SPOT_WEIGHT)
           WHEN 0 THEN SUM(j.MAN_SPOT_WT)
           ELSE SUM(w.SPOT_WEIGHT)
         END TONS
      from TC c, TC_LOAD_JOBS j, SPOT_WEIGHTS w, STATIONS s
    where c.TC_ID = j.TC_ID
       and FN_STN_KEY(j.FACTORY_ID, j.STATION_ID) = s.KEY_ID
       and j.LOAD_RATE_ID = w.LOAD_RATE_ID
       and c.DATE_INDEX = w.DATE_INDEX
       and j.FACTORY_ID = :P2053_ORG_ID
       and c.DATE_INDEX BETWEEN to_date(:P2053_DT,'MM/DD/YYYY') AND to_date(:P2053_DT,'MM/DD/YYYY') +15
    group by s.SHORT_NM||' ('||j.STATION_ID||') '||j.PILE_CODE_ALT_FLAG

  • Help with Inner Join query in SQL

    Hope someone can help with this, as this is quite an involved project for me, and I'm just about there with it.
    My table structure is :
    table_packages
    packageID
    package
    packageDetails
    etc
    table_destinations
    destinationID
    destination
    destinationDetails
    etc
    table_packagedestinations
    packageID
    destinationID
    ..so nothing that complicated.
    So the idea is that I can have a package details page which shows the details of the package, along any destinations linked to that package via the packagedestinations table.
    So this is the last part really - to get the page to display the destinations, but I'm missing something along the way....
    This is the PHP from the header, including my INNER JOIN query....
    PHP Code:
    <?php
    $ParampackageID_WADApackages = "-1";
    if (isset($_GET['packageID'])) {
      $ParampackageID_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
    $ParamSessionpackageID_WADApackages = "-1";
    if (isset($_SESSION['WADA_Insert_packages'])) {
      $ParamSessionpackageID_WADApackages = (get_magic_quotes_gpc()) ? $_SESSION['WADA_Insert_packages'] : addslashes($_SESSION['WADA_Insert_packages']);
    $ParampackageID2_WADApackages = "-1";
    if (isset($_GET['packageID'])) {
      $ParampackageID2_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
    mysql_select_db($database_connPackages, $connPackages);
    $query_WADApackages = sprintf("SELECT packageID, package, costperpax, duration, baselocation, category, dateadded, agerange, hotel, educational_tours, field_trips, corporate_outings, plant_visits, budget_package, rollingtours, teambuilding, description, offer FROM packages WHERE packageID = %s OR ( -1= %s AND packageID= %s)", GetSQLValueString($ParampackageID_WADApackages, "int"),GetSQLValueString($ParampackageID2_WADApackages, "int"),GetSQLValueString($ParamSessionpackageID_WADApackages, "int"));
    $WADApackages = mysql_query($query_WADApackages, $connPackages) or die(mysql_error());
    $row_WADApackages = mysql_fetch_assoc($WADApackages);
    $totalRows_WADApackages = mysql_num_rows($WADApackages);
    $colname_educationalDestinations = "1";
    if (isset($_GET['PackageID'])) {
      $colname_educationalDestinations = (get_magic_quotes_gpc()) ? packageID : addslashes(packageID);
    mysql_select_db($database_connPackages, $connPackages);
    $query_educationalDestinations = sprintf("SELECT * FROM destinations INNER JOIN (packages INNER JOIN packagedestinations ON packages.packageID = packagedestinations.packageID) ON destinations.destinationID = packagedestinations.destinationID WHERE packages.packageID = %s ORDER BY destination ASC", GetSQLValueString($colname_educationalDestinations, "int"));
    $educationalDestinations = mysql_query($query_educationalDestinations, $connPackages) or die(mysql_error());
    $row_educationalDestinations = mysql_fetch_assoc($educationalDestinations);
    $totalRows_educationalDestinations = mysql_num_rows($educationalDestinations);
    ?>
    And where I'm trying to display the destinations themselves, I have : 
    <table>
            <tr>
                     <td>Destinations :</td>
                </tr>
               <?php do { ?>
            <tr>
                 <td><?php echo $row_educationalDestinations['destination']; ?></td>
            </tr>
            <?php } while ($row_educationalDestinations = mysql_fetch_assoc($educationalDestinations)); ?>
    </table>
    If anyone could have a quick look and help me out that would be much appreciated - not sure if its my SQL at the top, or the PHP in the page, but either way it would be good to get it working. 
    Thanks.

    First off, you need to get the database tables so that there is a relationship between them.
    In fact, if there is a one to one relationship, then it may be better to store all of your information in one table such as
    table_packages
    packageID
    package
    packageDetails
    destination
    destinationDetails
    etc
    If there is a one to many relationship, then the following would be true
    packages
    packageID
    package
    packageDetails
    etc
    destinations
    destinationID
    packageID
    destination
    destinationDetails
    etc
    The above assumes that there are many destinations to one package with the relationship coloured orange.
    Once you have the above correct you can apply your query as follows
    SELECT *
    FROM packages
    INNER JOIN destinations
    ON packages.packageID = destinations.packageID
    WHERE packages.packageID = %s
    ORDER BY destination ASC
    The above query will show all packages with relevant destinations

Maybe you are looking for