Help in Joining query

Hi, How I can get desired result. I am joining two tables but if date timeline does't exist in #two table then should show hyphen (-). Please help on this query. Thanks.
create table #one (code_p char(4), code_h char(2), code_date datetime)
insert into #one values ('DEHG','2','2010-01-01')
insert into #one values ('DEHG','2','2011-01-01')
insert into #one values ('DEHC','2','2009-01-01')
insert into #one values ('DEHG','2','2012-01-01')
create table #two (code_p char(4), code_h char(2), code_date datetime)
insert into #two values ('DEHG','2','2010-01-01')
insert into #two values ('DEHC','2','2009-01-01')
select p.code_p code_p_one, p.code_h code_h_one, p.code_date code_date_one,
p.code_p code_p_two, p.code_h code_h_two, p.code_date code_date_two from #one p join #two a on p.code_p = a.code_p
--Result from the above query
code_p_one code_h_one code_date_one code_p_two code_h_two code_date_two
DEHG     2    2010-01-01     DEHG     2     2010-01-01
DEHG     2    2011-01-01     DEHG     2     2010-01-01
DEHC     2    2009-01-01     DEHG     2     2009-01-01
DEHC     2    2012-01-01     DEHG     2     2009-01-01
--Desired result
code_p_one code_h_one code_date_one code_p_two code_h_two code_date_two
DEHG     2    2010-01-01     DEHG     2     2010-01-01
DEHG     2    2011-01-01     DEHG     2     -
DEHC     2    2009-01-01     DEHG     2     2009-01-01
DEHC     2    2012-01-01     DEHG     2     -

Try this:
select p.code_p code_p_one, p.code_h code_h_one, p.code_date code_date_one,
p.code_p code_p_two, p.code_h code_h_two, ISNULL(CONVERT(varchar(50),a.code_date,121),'-') code_date_two
from #one p
left join #two a on p.code_p = a.code_p and p.code_date=a.code_date
If this post answers your query, please click "Mark As Answer" or "Vote as Helpful".

Similar Messages

  • Need help on join query

    Hi All,
    Please help me on the below join condition,
    >SELECT * FROM ESTIMATE_LINE WHERE JOB_ID = '214582' AND ESTIMATE_ID = 2;
    Output : Returns 1 row,
    >SELECT * FROM ESTIMATE_ACCOUNTING_LINE WHERE JOB_ID = '214582' AND ESTIMATE_ID = 2;
    Output : Returns 3 rows,
    I would like to add these two outputs as on, Finally i've to get 4 rows in the output,
    For that am writing the query like this,
    SELECT EL.*,EAL.*
    FROM ESTIMATE_LINE EL,
    ESTIMATE_ACCOUNTING_LINE EAL
    WHERE EL.JOB_ID = EAL.JOB_ID (+)
    AND EL.ESTIMATE_ID = EAL.ESTIMATE_ID (+)
    AND EAL.JOB_ID = '214582'
    AND EL.ESTIMATE_ID = 2,
    It is not giving the exact output, the common fields are there in the join condition,
    Can some one please re write the query for expected output..
    I am trying it but not getting the exact output,Unable to find out where the mistake is ...
    Thanks,
    gra

    Hi,
    First, let me make sure I undersatnd the problem.
    You have a query that lookas for information about a given job_id and estimate_id the estimate_line table. This query produces X rows.
    You have another query that lookas for information about the same job_id and estimate_id the estimate_accounting__line table. This query produces Y rows.
    You want to get the same results in one query that produces X+Y rows.
    That sounds like a job for UNION, not a join.
    If the two queries produces the same number of columns, and the data types of the columns are similiar, then you can just write the two queries together. Instead of a semicolon at the end of the first query, you'll say UNION (or UNION ALL):
    SELECT * FROM ESTIMATE_LINE            WHERE JOB_ID = '214582' AND ESTIMATE_ID = 2
    UNION ALL
    SELECT * FROM ESTIMATE_ACCOUNTING_LINE WHERE JOB_ID = '214582' AND ESTIMATE_ID = 2;If the columns are not the same, you'll need to call some conversion functions, or add literal columns (such as NULL) to the queries.
    If you need help, post a little sampe data (CREATE TABLE and INSERT statements) and the results you want from that data.

  • 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 in Join Select Query

    Hi, Please help on the Select Join query. I want to compare code_stat_system1/code_stat_system2 and code_date_system1 /code_date_system2 column from table #system1 and #system2 but there is 2 rule to get correct row from table #system1 and #system2.
    Rule 1: We need to get max(code_date_system1) record from #system1  for every code_system1 for compare.
    Rule 1: We need to get max(code_date_system2) record from #system2  BUT BEFORE THE RECORD OF 'DKNOW' OF code_stat_system2 for every code_system2 for compare.
    drop table #system1,#system2
    create table #system1
    (Code_system1 varchar(10),code_stat_system1 varchar(10),code_date_system1 datetime)
    Insert into #system1 values ('10','Dead','2013-01-01')
    Insert into #system1 values ('10','Dead','2013-12-30')
    Insert into #system1 values ('10','UnOpen','2014-10-01')
    Insert into #system1 values ('10','Open','2014-11-01')   --This record should max(code_stat_system1) for compare
    Insert into #system1 values ('20','Dead','2013-12-01')
    Insert into #system1 values ('20','Dead','2013-12-30')
    Insert into #system1 values ('20','Open','2014-08-01')
    Insert into #system1 values ('20','UnOpen','2014-09-01') --This record should max(code_stat_system1) for compare
    create table #system2
    (Code_system2 varchar(10),code_stat_system2 varchar(10),code_date_system2 datetime)
    Insert into #system2 values ('10','Dead','2013-01-01')
    Insert into #system2 values ('10','Dead','2013-12-30')
    Insert into #system2 values ('10','Open','2014-10-01')
    Insert into #system2 values ('10','UnOpen','2014-12-01') --This record should max(code_stat_system2) which is before 'DKNOW' for compare
    Insert into #system2 values ('10','DKNOW','2015-01-01')
    Insert into #system2 values ('10','DKNOW','2015-02-01')
    Insert into #system2 values ('20','Dead','2013-12-01')
    Insert into #system2 values ('20','Dead','2013-12-30')
    Insert into #system2 values ('20','Open','2014-08-01')
    Insert into #system2 values ('20','UnOpen','2014-09-01') --This record should max(code_stat_system2) which is before 'DKNOW' for compare
    Insert into #system2 values ('20','DKNOW','2015-01-01')
    Insert into #system2 values ('20','DKNOW','2015-02-01')
    --Desired Output
    Code_system1  code_stat_system1  code_date_system1  Code_system1   code_stat_system2  code_date_system1    Rrmk_code_stat         Rrmk_code_date
    10            Open           2014-11-01        10          UnOpen         
    2014-12-01         Codes not matching     Dates not matching
    20            UnOpen         2014-09-01        20          UnOpen         
    2014-09-01         Codes matching          Dates matching
    Thanks.

    drop table #system1,#system2
    create table #system1
    (Code_system1 varchar(10),code_stat_system1 varchar(10),code_date_system1 datetime)
    Insert into #system1 values ('10','Dead','2013-01-01')
    Insert into #system1 values ('10','Dead','2013-12-30')
    Insert into #system1 values ('10','UnOpen','2014-10-01')
    Insert into #system1 values ('10','Open','2014-11-01') --This record should max(code_stat_system1) for compare
    Insert into #system1 values ('20','Dead','2013-12-01')
    Insert into #system1 values ('20','Dead','2013-12-30')
    Insert into #system1 values ('20','Open','2014-08-01')
    Insert into #system1 values ('20','UnOpen','2014-09-01') --This record should max(code_stat_system1) for compare
    create table #system2
    (Code_system2 varchar(10),code_stat_system2 varchar(10),code_date_system2 datetime)
    Insert into #system2 values ('10','Dead','2013-01-01')
    Insert into #system2 values ('10','Dead','2013-12-30')
    Insert into #system2 values ('10','Open','2014-10-01')
    Insert into #system2 values ('10','UnOpen','2014-12-01') --This record should max(code_stat_system2) which is before 'DKNOW' for compare
    Insert into #system2 values ('10','DKNOW','2015-01-01')
    Insert into #system2 values ('10','DKNOW','2015-02-01')
    Insert into #system2 values ('20','Dead','2013-12-01')
    Insert into #system2 values ('20','Dead','2013-12-30')
    Insert into #system2 values ('20','Open','2014-08-01')
    Insert into #system2 values ('20','UnOpen','2014-09-01') --This record should max(code_stat_system2) which is before 'DKNOW' for compare
    Insert into #system2 values ('20','DKNOW','2015-01-01')
    Insert into #system2 values ('20','DKNOW','2015-02-01')
    ;with mycte1 as (select * ,row_number() Over (partition by Code_system1 Order by code_date_system1 Desc ) rn from #system1)
    ,mycte2 as (select *,row_number() Over (partition by Code_system2 Order by code_date_system2 Desc ) rn2 from #system2
    where code_stat_system2<>'DKNOW')
    Select m1.Code_system1, m1.code_stat_system1, m1.code_date_system1, Code_system2, code_stat_system2,code_date_system2 ,
    case When code_date_system1=code_date_system2 then 'Dates matching' else 'Dates not matching' End as checkDate,
    case When code_stat_system1=code_stat_system2 then 'Codes matching' else 'Codes not matching' End as checkStat
    from mycte1 m1 inner join mycte2 m2 on m1.Code_system1= m2.Code_system2 and m1.rn=m2.rn2
    Where m1.rn=1

  • 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

  • Join query help

    hi
    i am encountering error like the values not getting populated in internal table though values are in dbtable...so if u can help me out in the join query it will be of gr8 help
    SELECT a1~guid a1~posting_date a1~process_type
           b1~sales_org b1~division b1~dis_channel
           INTO CORRESPONDING FIELDS OF TABLE it_ordel
           FROM ( ( crmd_orderadm_h AS a1 INNER JOIN crmd_link AS c1 ON a1~guid  = c1~guid_hi )
                    INNER JOIN crmd_orgman AS b1 ON c1~guid_hi = b1~guid )
           WHERE c1~objtype_hi = '05'
           AND   c1~objtype_set = '21'.
        AND   a1~process_type IN so_prst
           AND   a1~posting_date IN so_podt
           AND   b1~division     IN so_div.
    thnx

    SELECT a1~guid a1~posting_date a1~process_type
           b1~sales_org b1~division b1~dis_channel
           INTO CORRESPONDING FIELDS OF TABLE it_ordel
           FROM ( ( crmd_orderadm_h AS a1 INNER JOIN crmd_link AS c1 ON a1~guid  = c1~guid_hi )
                    INNER JOIN crmd_orgman AS b1 ON c1~guid_hi = b1~guid )
           WHERE c1~objtype_hi = '05'
           AND   c1~objtype_set = '21'.
        AND   a1~process_type IN so_prst
           AND   a1~posting_date IN so_podt
           AND   b1~division     IN so_div.
    SELECT a1~guid a1~posting_date a1~process_type
           b1~sales_org b1~division b1~dis_channel
           INTO CORRESPONDING FIELDS OF TABLE it_ordel
           FROM ( ( crmd_orderadm_h AS a1 INNER JOIN crmd_link AS c1 ON a1~guid  = c1~guid_hi )
                    INNER JOIN crmd_orgman AS b1 ON c1~guid_hi = b1~guid )
           WHERE c1~objtype_hi = '05'
           AND   c1~objtype_set = '21'    ".              delete that period its wrong
        AND   a1~process_type IN so_prst
           AND   a1~posting_date IN so_podt
           AND   b1~division     IN so_div.

  • How to get Hierarchical XML File from a Database Join Query !

    Hi,
    How can i get a Hierarchical XML File from a Database Join Query ?
    Any join query returns repeated values as below:
    BD17:SQL>select d.dname, e.ename, e.sal
    2 from dept d
    3 natural join
    4 emp e
    5 /
    DNAME ENAME SAL
    ACCOUNTING CLARK 2450
    ACCOUNTING KING 5000
    ACCOUNTING MILLER 1300
    RESEARCH SMITH 800
    RESEARCH ADAMS 1100
    RESEARCH FORD 3000
    RESEARCH SCOTT 3000
    RESEARCH JONES 2975
    SALES ALLEN 1600
    SALES BLAKE 2850
    SALES MARTIN 1250
    SALES JAMES 950
    SALES TURNER 1500
    SALES WARD 1250
    14 rows selected.
    We tried use DBMS_XMLQUERY to generate a xml file, but it was unable to get xml in Hierarchical format.
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    - <ROWSET>
    - <ROW num="1">
    <DNAME>ACCOUNTING</DNAME>
    <ENAME>CLARK</ENAME>
    <SAL>2450</SAL>
    </ROW>
    - <ROW num="2">
    <DNAME>ACCOUNTING</DNAME>
    <ENAME>KING</ENAME>
    <SAL>5000</SAL>
    </ROW>
    - <ROW num="3">
    <DNAME>ACCOUNTING</DNAME>
    <ENAME>MILLER</ENAME>
    <SAL>1300</SAL>
    </ROW>
    - <ROW num="4">
    <DNAME>RESEARCH</DNAME>
    <ENAME>SMITH</ENAME>
    <SAL>800</SAL>
    </ROW>
    - <ROW num="5">
    <DNAME>RESEARCH</DNAME>
    <ENAME>ADAMS</ENAME>
    <SAL>1100</SAL>
    </ROW>
    - <ROW num="6">
    <DNAME>RESEARCH</DNAME>
    <ENAME>FORD</ENAME>
    <SAL>3000</SAL>
    </ROW>
    - <ROW num="7">
    <DNAME>RESEARCH</DNAME>
    <ENAME>SCOTT</ENAME>
    <SAL>3000</SAL>
    </ROW>
    - <ROW num="8">
    <DNAME>RESEARCH</DNAME>
    <ENAME>JONES</ENAME>
    <SAL>2975</SAL>
    </ROW>
    - <ROW num="9">
    <DNAME>SALES</DNAME>
    <ENAME>ALLEN</ENAME>
    <SAL>1600</SAL>
    </ROW>
    - <ROW num="10">
    <DNAME>SALES</DNAME>
    <ENAME>BLAKE</ENAME>
    <SAL>2850</SAL>
    </ROW>
    - <ROW num="11">
    <DNAME>SALES</DNAME>
    <ENAME>MARTIN</ENAME>
    <SAL>1250</SAL>
    </ROW>
    - <ROW num="12">
    <DNAME>SALES</DNAME>
    <ENAME>JAMES</ENAME>
    <SAL>950</SAL>
    </ROW>
    - <ROW num="13">
    <DNAME>SALES</DNAME>
    <ENAME>TURNER</ENAME>
    <SAL>1500</SAL>
    </ROW>
    - <ROW num="14">
    <DNAME>SALES</DNAME>
    <ENAME>WARD</ENAME>
    <SAL>1250</SAL>
    </ROW>
    </ROWSET>
    Thank you for some help.
    Nelson Alberti

    Hi,
    I wrote a general ABAP program which can be configured to grab contrent from an URL and post that content as a new PI message into the integration adapter .... from that point on normal PI configuration can be used to route it to anywhere ...
    It can be easily scheduled as a background job to grab content on a daily basis etc ...
    Regards,
    Steven

  • Problem getting results with no unique key in a joined query

    I created a descriptor to do a joined query, which generated a query in log as:
    Select t0.empID,t1.empID, t1.phone from Emp t0, Phone t1
    where t0.empId=t1.empId and t0.empId=1001
    When I run it, I got the result as:
    1001,1001,9999999
    1001,1001,9999999
    The correct result should be (I copy and paste the query from log into SQL-Plus):
    1001,1001,9999999
    1001,1001,1234455
    I suspect this is caused by Toplink caching objects by primary key. I wonder if anybody has a solution for this.
    My descriptor is created using WorkBench. Emp is the primary table, Phone as additional table linked by foreignKey empId.
    The join is implemented by modifying the descriptor as the following:
    ExpressionBuilder builder = new ExpressionBuilder();
    descriptor.getQueryManage()
    .setMultipleTableJoinExpression(
    builder.getField("EMP.EMPID").equal(
    builder.getField("EMP.EMPID")));
    descriptor.disableCacheHits();
    I'd really appreciate your help.

    I am implementing a people search function. The batch reading is quite expensive if toplink does a read query for every person. A customized query requires only one database access, the other way may requires hundreds.
    I don't want to use the cache either in this case because the database is also accessed by legacy system which cann't notify toplink any updates.
    I opened a TAR on this and the solution I got is to use ReportQuery rathen than ReadAllQuery. The only problem here is that now I have to map the query result to my class manually.

  • Adding a field to rhe join query

    Dear Friends,
    I need your help in adding a field to a join query.
    I have created a reort using join(SQVI). Now i want to add an addition field to that report. The issue is the field i am looking at is stored in structure. Is there any way i can add this field....
    Sanjay

    It is not possible here (in SQVI).
    you have to Go with Query.
    SQ02 using this Create infoset, add all the tables , here include that structure field, and then add the logic to populate the field.
    Now go to SQ01 and create Query.

  • Inner join query used with 7 Database tables

    HI All,
    In a report they used the Inner join Query with 6 Data base table..now there is a performance issue with at query.
    its taking so much of time to trigger that query. Please help how to avoid that performance issue for that.
    In that 2 database tables containing lakhs of records..
    According to my knowledge it can be avoided by using secondary indexs for those 2 database tables..
    and by replacing the Inner join Query with FOR ALL ENTRIES statement.
    i want how to use the logic by using FORALL ENTRIES statement for this..
    So, please give you proper suggestion to avoid this issue..
    Thanking you.
    Moderator message: Please Read before Posting in the Performance and Tuning Forum
    Edited by: Thomas Zloch on Oct 16, 2011 10:27 PM

    Hi,
    And what do you mean with "they used"? If "SAP used" then yo will need to ask a SAP for note
    FOR ALL ENTRIES is quite good described in help. Please search forum also.
    Without query it won't be possible to tell how it can be optimized, however you can try to use SE30/SAT and ST05. Maybe it will help you.
    BR
    Marcin Cholewczuk

  • Help wit the query

    I need help with the query
    Here is what I need
    For a particular comm record if there is no Salary record where comm:Date = Salary:Date, then
    • Find maximum dated Salary record as of comm:Date.
    • Clone this record and set Salary:Date = comm:Date
    • Set Salary:rate = comm:rate
    Like wise for a particular Salary record If there is no comm record where Salary:Date = comm:Date then
    • Find maximum effective dated comm record as of Salary:Date
    • Apply Rate 2 amount from this maximum effective dated record to Salary record i.e. Set Salary:rate = comm:rate
    Example
    Salary Table :
    ID Sal_Date Rate Hours
    1 07/01/2011 400.00 40
    2 02/15/2011 200.00 40
    3 01/01/2011 160.00 40
    Sal_comm Table:
    Sal_Date comm_Rate
    1 07/01/2011 10.00
    4 03/01/2011 7.50
    3 01/01/2011 4.00
    I need to merge comm_Rate column in Salary table, since there is no salary record as off 03/01/2011, I need to find the maximum dated salary record as of 03/01/2011
    i.e. the record dated 02/15/2011. Now I need to clone that salary record, set the SAL_date as 03/01/2011 and update Rate2 amount. So the record set will be like:
    Sal_Date:
    id sal_Date Rate Hours comm_Rate
    1 07/01/2011 400.00 40 10.00
    4 03/01/2011 200.00 40 7.50
    2 02/15/2011 200.00 40 4.00
    3 01/01/2011 160.00 40 4.00

    So you need all used dates as the "driving" dataset. And you need the according data for each of these.
    WITH salary_table as
    (select 1 id,to_date('07/01/2011','MM/DD/YYYY')sal_date,400 rate,40 hours from dual union all
    select 2 id,to_date('02/15/2011','MM/DD/YYYY')sal_date,200 rate,40 hours from dual union all
    select 3 id,to_date('01/01/2011','MM/DD/YYYY')sal_date,160 rate,40 hours from dual),
    sal_comm as
    (select 1 id,to_date('07/01/2011','MM/DD/YYYY')sal_date,10 comm_Rate from dual union all
    select 4 id,to_date('03/01/2011','MM/DD/YYYY')sal_date,7.5 comm_Rate from dual union all
    select 3 id,to_date('01/01/2011','MM/DD/YYYY')sal_date,4 comm_Rate from dual)
    select to_char(all_dates.sal_date,'MM/DD/YYYY') sal_date,sal.rate,sal.hours,com.comm_rate
    from (select sal_date from salary_table
          union
          select sal_date from sal_comm) all_dates
    inner join (select s1.*,lead(sal_date-1,1,to_date('31/12/9999','DD/MM/YYYY')) over (order by sal_date) next_sal_date
               from salary_table s1) sal
      on (all_dates.sal_date between sal.sal_date and sal.next_sal_date)
    inner join (select s1.*,lead(sal_date-1,1,to_date('31/12/9999','DD/MM/YYYY')) over (order by sal_date) next_sal_date
               from sal_comm s1) com
      on (all_dates.sal_date between com.sal_date and com.next_sal_date)
    order by   all_dates.sal_date desc;
    SAL_DATE   RATE                   HOURS                  COMM_RATE             
    07/01/2011 400                    40                     10                    
    03/01/2011 200                    40                     7.5                   
    02/15/2011 200                    40                     4                     
    01/01/2011 160                    40                     4                     
         

  • MV Incremental Refresh on join query of remote database tables

    Hi,
    I am trying to create a MV with incremental refresh option on a join query with 2 tables of remote database.
    Created MV logs on 2 tables in the remote database.
    DROP MATERIALIZED VIEW LOG ON emp;
    CREATE MATERIALIZED VIEW LOG ON emp WITH ROWID;
    DROP MATERIALIZED VIEW LOG ON dept;
    CREATE MATERIALIZED VIEW LOG ON dept WITH ROWID;
    Now, trying to create the MV,
    CREATE MATERIALIZED VIEW mv_emp_dept
    BUILD IMMEDIATE
    REFRESH FAST
    START WITH SYSDATE
    NEXT SYSDATE1/(24*15)+
    WITH PRIMARY KEY
    AS
    SELECT e.ename, e.job, d.dname FROM emp@remote_db e,dept@remote_db d
    WHERE e.deptno=d.deptno
    AND e.sal>800;
    Getting ORA-12052 error.
    Can you please help me.
    Thanks,
    Anjan

    Primary Key is on EMPNO for EMP table and DEPTNO for DEPT table.
    Actually, I have been asked to do an feasibility test whether incremental refresh can be performed on MV with join query of 2 remote database tables.
    I've tried with all combinations of ROWID and PRIMARY KEY, but getting different errors. From different links, I found that it's possible, but cannot create any successful testcase anyway.
    It will be very much helpful if you can correct my example or tell me the restrictions in this case.
    Thanks,
    Anjan

  • Sql join query join

    Hi I have 3 tables.
    Table                   columns
    1. Buy                     buyer,sellername
    2. IM                      product,hdate,UOM,dept,sec,subsec
    3. stud                    dept,sec,subsecRequired O/P with columns as :
    buyer   product   dept  sec  subsec
    ---------------------------------------------------so please send me the join query for this.
    Thank you.

    I am getting the output with the above mentioned query as
    buyer   product  dept    class     subsecs
    90      glass    203     310      234
    120     glass    203     310      234
    354     glass    203     310      234
    435     belts    330     243      890
    435     belts    330     243      890
    ...like this I am getting the result...
    So please help me in this issue..
    Thank you.

  • Help build a query !!!

    There are two tables. One consists of members with expenses and next with fixed percentile. I need to build a single query based upon following
    1. Need to know the number of members that fall under a fixed range of percent like 10%, 40%, 50%. Suppose, total no of members = 50 then
    10% -> 5
    40% -> 20
    50% -> 25
    2. Now I need to rank the members as per their expenses. So, if following be the expenses of the members sorted by expenses
    A1 100
    A2 99
    A3 98
    A4 97
    A5 96
    A6 95
    A50 50
    then
    total expense should be found out as
    10% [sum of top 5 : From A1 to A5] = 100 + 99 + 98 + 97 + 96 = 490
    40% [sum of next 20: From A6 to A26]
    50% [sum of next 25: From A27 to A50]
    Please help !!!!!
    Edited by: josleen on Jan 11, 2010 7:50 AM

    Hi,
    There are a number of analytic functions for dealing with percentiles.
    Depending on how you want to handle ties, how you count duplicate values, and other factors, PERCENT_RANK might be best for this problem.
    You really should post the information Centinul requested whenever you have a question.
    If you can phrase your question in terms of commonly available tables, then you don't have to post them.
    For example, to group employees from the scott.emp table according to their salaries, and get a total of salaries by group, you could create a groups table and join it to the emp table, like this:
    CREATE TABLE     groups
    (      seq_id     NUMBER
    ,      label     VARCHAR2 (20)
    ,      low_pct     NUMBER      -- lowest number IN this group
    ,      high_pct     NUMBER      -- lowest number NOT IN this group, but in the next highest group
    INSERT INTO groups (seq_id, label, low_pct, high_pct) VALUES (1, 'Top 10%',     0,     10);
    INSERT INTO groups (seq_id, label, low_pct, high_pct) VALUES (2, '10%-50%',     10,     50);
    INSERT INTO groups (seq_id, label, low_pct, high_pct) VALUES (3, 'Bottom 50%',     50,     101);
    COMMIT;
    WITH     got_pct          AS
         SELECT ename
         ,      sal
         ,      100 * PERCENT_RANK () OVER ( ORDER BY sal DESC
                                                  ,          empno
                               )     AS pct
         FROM   scott.emp
    SELECT    g.label
    ,       SUM (p.sal)     AS group_total
    FROM       got_pct     p
    JOIN       groups     g     ON     p.pct     >= g.low_pct
                          AND     p.pct     <  g.high_pct
    GROUP BY  g.label
    ORDER BY  MIN (g.seq_id)
    ;Output:
    LABEL                GROUP_TOTAL
    Top 10%                     8000
    10%-50%                    12875
    Bottom 50%                  8150If you need help understanding a query with sub-queries, it helps to run the sub-query by iteself.
    In this case:
    WITH     got_pct          AS
         SELECT ename
         ,      sal
         ,      100 * PERCENT_RANK () OVER ( ORDER BY sal DESC
                                                  ,          empno
                               )     AS pct
         FROM   scott.emp
    SELECT     *
    FROM     got_pct
    ;produces this output:
    ENAME             SAL        PCT
    KING             5000          0
    SCOTT            3000 7.69230769
    FORD             3000 15.3846154
    JONES            2975 23.0769231
    BLAKE            2850 30.7692308
    CLARK            2450 38.4615385
    ALLEN            1600 46.1538462
    TURNER           1500 53.8461538
    MILLER           1300 61.5384615
    WARD             1250 69.2307692
    MARTIN           1250 76.9230769
    ADAMS            1100 84.6153846
    JAMES             950 92.3076923
    SMITH             800        100In case of a tie, PERCENT_RANK assigns the same result to all rows with the same input value. The reason I included empno in the analytic ORDER BY clause was to prevent ties. Otherwise, both SCOTT and FORD (with the exact same sal=3000) would be assigned pct=7.69230769, and the "Top 10%" would then include 3 out of 14 rows (over 21% of the rows), which, outside of Lake Woebegone, shouldn't happen.
    Edited by: Frank Kulash on Jan 11, 2010 11:02 AM
    Explanation added.

  • Join query with cfoutput group

    Hi,
    I have the problem with join query and output the goup by, can anyone helps please?
    1: worked fine
    <cfquery name="qOrgs" datasource="#GetDSN()#">
    select org
    from cat
    </cfquery>
    <cfoutput query="qOrgs" group="org">
    #org#<br />
    </cfoutput>
    2: not work, not grouping and display duplicated.
    <cfquery name="qOrgs" datasource="#GetDSN()#">
    select org
      from user u
      inner JOIN cat c
      on u.userid= c.userid
    </cfquery>
    <cfoutput query="qOrgs" group="org">
    #org#<br />
    </cfoutput>
    Thanks

    To expand on Dan's answer;
    The "group" property of the <cfoutput...> tag is fairly simplistic.  All it actuall does is conditionally output content whenever the value of the specified group column changes.
    So if you do not use an ORDER BY clause in your SQL to group the values of that column together (or they don't naturally group because of the current state of the data in the database) then the output is probably not going to be as desired.

Maybe you are looking for