PL/SQL Inner Join

Hello.
I'm trying to join 2 tables. The problem is one record in 1st table is in simple latin (f.e. MODIFIED) and the second one in 2nd table includes polish symbols (f.e. MÓDIFIĘD). I want to ignore polish symbols and simplify them into latin coding. Since today I used to join tables with COLLATE (sql). Is there any equivalent of COLLATE function in PL/SQL?
In summary.
1st in:
1234 MODIFIED NAME SURNAME PRODUCT
2nd in:
1 MÓDIFIĘD DATA ADRESS
3rd - results:
MODIFIED NAME SURNAME ADRESS
I'm using Oracle SQL Developer. Database version - latest.
Thanks. Sincerely - Marcin.
Edited by: 888729 on 2011-09-30 03:17

Thanks for quick response, but the problem is not solved. I'll try to show you my objective more clearly.
888729 wrote:
SELECT DISTINCT nt.id, nt.priority, nt.determined_on, nt.assigned_group, assigned.email, FROM notifications nt
INNER JOIN ASSIGNED ON ASSIGNED.ASSIGNED_GROUP = nt.ASSIGNED_GROUP
WHERE nt.DETERMINED_ON > (SYSDATE-10)
So, I have two tables: notifications and assigned. In the first table (notifications) I have column ASSIGNED_GROUP and in the second one (assigned) the same column ASSIGNED_GROUP (both the same type). If I join those two tables there will be a problem with coding. For example:
table notifications, cell ASSIGNED_GROUP:
ABC_MAGIC
table assigned, cell ASSIGNED_GROUP:
ĄBĆ_MĄGIĆ
I need those rows to be joined together. So I need to ignore polish symbols in 2nd line of my script (INNER JOIN).

Similar Messages

  • Dynamic SQL - Inner Join

    I just starting to Learn and use Dynamic SQL. 
    I am trying use a inner join query in dynamic SQL 
    for Example say 'Select A.id as Itemid , A.name as Itemname from TableA A inner join TableB B On A.ID = B.ID where B.ID typeid = 1 '
    for some reason this is not working . i for sure know the query works as when i run the query it works fine. when i try to run it dynamically it give me blank values.
    Please let me know if you need more information.
    Appreicate Your help!!
    Thanks,
    Chaitanya 

    Here is an example for dynamic SQL from BOL:
    DECLARE @IntVariable int;
    DECLARE @SQLString nvarchar(500);
    DECLARE @ParmDefinition nvarchar(500);
    /* Build the SQL string one time.*/
    SET @SQLString =
    N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID
    FROM AdventureWorks2012.HumanResources.Employee
    WHERE BusinessEntityID = @BusinessEntityID';
    SET @ParmDefinition = N'@BusinessEntityID tinyint';
    /* Execute the string with the first parameter value. */
    SET @IntVariable = 197;
    EXECUTE sp_executesql @SQLString, @ParmDefinition,
    @BusinessEntityID = @IntVariable;
    /* Execute the same string with the second parameter value. */
    SET @IntVariable = 109;
    EXECUTE sp_executesql @SQLString, @ParmDefinition,
    @BusinessEntityID = @IntVariable;
    Basically any query can be run as dynamic SQL.  However, static SQL is the first choice. Use dynamic SQL if needed.
    Dynamic SQL examples:
    http://www.sqlusa.com/bestpractices/dynamicsql/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • INNER JOIN, MX 7, column name error

    I am running or attempting to run the att'd query in CF MX
    7.0 and getting an error because I then run:
    <CFOUTPUT QUERY="getNutes" group="NUTR_NO">
    <CFSET VALUE = 0>
    <CFOUTPUT>
    <CFIF Day EQ "T">
    <CFSET VALUE = VALUE + (getNutes.Total_WT *
    getNutes.NUTR_VAL/100) / getDays.RecordCount>
    <CFELSE>
    <CFSET VALUE = VALUE + (getNutes.Total_WT *
    getNutes.NUTR_VAL/100)>
    </CFIF>
    </CFOUTPUT>
    To sum the nutrient contents...
    This worked fine under CF 5... but I am getting a 'NUTR_NO
    does not specify a column name in the query'.
    Any thoughts???
    Query follows:

    > Yep... it's worse... it appears that MX does not support
    the sql inner join or
    > outer join... sigh...
    Don't be ridiculous. You're showing a fundamental lack of
    understanding of
    how CF handles database interaction. When you use
    <cfquery> to "create" a
    recordset, all CF does is resolve any embedded CF (tags,
    functions,
    variables, etc), and passes the resulting string to the DB.
    The DB then
    processes it and returns a recordset. So CF doesn't "support"
    any sort of
    SQL syntax. Now does it claim to; nor does it try to; nor is
    it
    appropriate for it to.
    If you're having problems with your returned recordset, the
    first thing you
    should do is <cfdump> it (or part of it) and check that
    you're getting back
    what you're *assuming* you're getting back.
    The second thing you should do is lose the SELECT *. Specify
    the columns
    you want back. This is nothing to do with CF, it's just
    standard SELECT
    query advice. When you're joining tables, you hardly ever
    want ALL the
    columns back, and if it's one of those rare occasions you DO
    want all of
    them, you should still specify a SELECT clause so you can
    distinguish
    between same-named columns (which seems to be your problem
    here).
    Adam

  • 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

  • Why can't i use "INNER JOIN" in a query for SQL Server with JDBC??????

    Hi,
    I'm trying to execute some SQL queries and I just don't understand what's wrong.
    I�m using Tomcat and SQL Server in order to do this, but when I�m try to execute a query with a INNER JOIN statements Tomcat raise a SQL exception... at the very first time I thought there was a problem with database connection but I realize that a simple query to a table works pretty well. then I found out some problems with JDBC:ODBC.... so I install JDBC for SQL Server 2000 and test with the same simple query and works..... so, I come to a conclusion.... INNER JOIN or JOIN statements can't be used in JDBC..... please... somebody tell I�m wrong and give me a hand...
    I'm using TOMCAT 4 and JDK 1.4 SQL Server 2000
    Error occurs when executeQuery() is called.... not prepareStatement().... ??????
    Driver DriverRecResult = (Driver)Class.forName(driver).newInstance();
    Connection ConnRecResult = DriverManager.getConnection(DSN,user,password);
    PreparedStatement StatementRecResult = ConnRecResult.prepareStatement(query);
    ResultSet RecResult = StatementRecResult.executeQuery(); <---- Exception raise here
    So much tahnks in advance,

    That's exactly what I think, driver it's raising the exception, but I don't know why.... i test the same query with INNER JOIN directly from SQL Query Analyser and it's works perfectly, my problem ain't SQL, but JSP and JDBC 'cause i'm a newbie about these issues.
    Common sense tell me possible problems lie in SQLServer drivers 'cause i run the same pages on JRUN through jdbc:odbc and do works well, but by now i just depend on Tomcat.....
    I've installed SQL Server drivers for JDBC but i just find it doesn't work fully... could be the version of JDK i've installed? what version do i need?
    ( I'm running Tomcat 4 with JDK 1.4 & SQL Server 2000 W2K )
    thanks for reply.

  • Please tell me the  Three table INNER JOIN Sql statement

    Hi experts,
      I got requirement like by using INNER JOIN i have to write the code in MY program i.e using 3 tables VBAK VBAP and VBUK.And the common field is VBELN .SO please give the  INNER JOIN SQL statement for above three tables...
    vbak-vbeln,erdat
    vbap-vbeln,posnr
    vbuk-vbeln,RFSTK
    Thanks in Advance

    hi guglani  please see my total code b.caus DATA is not extracting...once see the code  correct error.
    DATA:V_VBELN TYPE VBAK-VBELN.      "VBAK,VBAP AND VBUK
    SELECT-OPTIONS SORDER FOR V_VBELN.
    TYPES:BEGIN OF T_VBAK,
         VBELN TYPE VBELN_VA,
         ERDAT TYPE ERDAT,
      END OF T_VBAK.
    TYPES:BEGIN OF T_VBAP,
           VBELN TYPE VBELN_VA,
            POSNR TYPE POSNR_VA,
      END OF T_VBAP.
    TYPES:BEGIN OF T_VBUK,
        VBELN TYPE VBELN,
      RFSTK TYPE RFSTK,
      END OF T_VBUK.
    TYPES:BEGIN OF FS,
       VBELN TYPE VBELN_VA,
         ERDAT TYPE ERDAT,
    POSNR TYPE POSNR_VA,
      RFSTK TYPE RFSTK,
      END OF FS.
    DATA:WA1 TYPE T_VBAK,
         WA2 TYPE T_VBAP,
         WA3 TYPE T_VBUK,
         WA TYPE FS.
    DATA:ITAB1 TYPE TABLE OF T_VBAK,
          ITAB2 TYPE TABLE OF T_VBAP,
          ITAB3 TYPE TABLE OF T_VBUK,
          ITAB TYPE TABLE OF FS.
    select a~vbeln a~erdat b~posnr c~rfstk
           from vbak as a inner join vbAP as b on a~vbeln = b~vbeln
                          inner join vbuk as c on a~vbeln = c~vbeln
    into table itab
    where A~vbeln eq SORDER.
    IF NOT ITAB IS INITIAL.
      SORT ITAB BY VBELN.
    ENDIF.
    LOOP AT ITAB INTO WA.
       WRITE:/ WA-VBELN,WA-ERDAT,WA-rfstk.
       ENDLOOP.
       CLEAR WA.
       REFRESH ITAB.

  • How to use Inner join of table as Source in Merge statement in SQL

    Hi All,
        I am trying to make source as multiple tables output using Join while coding there is no any syntax error but when i am executing this statement is giving following error
    Following is the query 
    Merge Into EmpDept Target
    Using (select E.Address,e.Design,e.EmailId,e.EmpId,e.Ename,e.ManagerId, e.Salary,D.DeptId,D.DeptName,D.Location from Employee E Inner join Dept D on E.DeptId=D.DeptId )As Source (Address,Design,EmailId,EmpId,EName,ManagerId,Salary,DeptId,DeptName,Location)
    On Source.EmpId=Target.EmpId
    when not matched then
    Insert (Target.Address,Target.Design,Target.EmailId,Target.EmpId,Target.Ename,Target.ManagerId, Target.Salary,Target.DeptId,Target.DeptName,Target.Location)
    values
    (Address,Design,EmailId,EmpId,EName,ManagerId, Salary,DeptId,DeptName,Location)
    When matched then 
    Update set Target.Address = Source.Address ,Target.Design = Source.Design,Target.EmailId      = Source.EmailId     ,Target.Ename       = Source.Ename      ,Target.ManagerId = Source.ManagerId , Target.Salary        = Source.Salary       ,Target.DeptId      = Source.DeptId      ,Target.DeptName = Source.DeptName ,Target.Location    = Source.Location;
    This is error while executing the above merge statement 
    The insert column list used in the MERGE statement cannot contain multi-part identifiers. Use single part identifiers instead.
    Please suggest me where i am wrong.. 
    Niraj Sevalkar

    MERGE INTO EmpDept Target
    Using (SELECT E.Address,
    e.Design,
    e.EmailId,
    e.EmpId,
    e.Ename,
    e.ManagerId,
    e.Salary,
    D.DeptId,
    D.DeptName,
    D.Location
    FROM Employee E
    INNER JOIN Dept D
    ON E.DeptId = D.DeptId) AS Source (Address, Design, EmailId, EmpId, EName, ManagerId, Salary, DeptId, DeptName, Location)
    ON Source.EmpId = Target.EmpId
    WHEN NOT matched THEN
    INSERT (Address,
    Design,
    EmailId,
    EmpId,
    Ename,
    ManagerId,
    Salary,
    DeptId,
    DeptName,
    Location)
    VALUES (Address,
    Design,
    EmailId,
    EmpId,
    EName,
    ManagerId,
    Salary,
    DeptId,
    DeptName,
    Location)
    WHEN matched THEN
    UPDATE SET Address = Source.Address,
    Design = Source.Design,
    EmailId = Source.EmailId,
    Ename = Source.Ename,
    ManagerId = Source.ManagerId,
    Salary = Source.Salary,
    DeptId = Source.DeptId,
    DeptName = Source.DeptName,
    Location = Source.Location;

  • INNER JOIN PROBLEM IN Microsoft SQL Server 2008 R2 Report Builder 3.0

    SELECT
    ,maximo_tbl_matrectrans.ponum
    ,maximo_tbl_po.description AS [maximo_tbl_po description]
    ,maximo_tbl_matrectrans.polinenum
    ,maximo_tbl_matrectrans.itemnum
    ,maximo_tbl_item.description AS [maximo_tbl_item description]
    FROM
    maximo_tbl_matrectran
    INNER JOIN maximo_tbl_po
    ON maximo_tbl_matrectrans.ponum = maximo_tbl_po.ponum
    INNER JOIN maximo_tbl_item
    ON maximo_tbl_matrectrans.itemnum = maximo_tbl_item.itemnum
    can you advise below picture in itemnum in show one value more time
    ponum polinenum maximo_tbl_a_po_description itemnum maximo_tbl_a_item_description
    D33-1021425 5 ASL REORDER HAZMAT 91G8110000071 DRUM, PLASTIC
    D33-1021425 5 ASL REORDER HAZMAT 91G8110000071 DRUM, PLASTIC
    D33-1020817 2 ASL REPLENISHMENT, D 91G6685000371 THERMOSTAT
    D33-1020817 2 ASL REPLENISHMENT, D 91G6685000371 THERMOSTAT
    D33-1020817 2 ASL REPLENISHMENT, D 91G6685000371 THERMOSTAT
    D33-1021365 2 ASL - D33DFAC STOCK 91G3920000081 CART, BIG WHEEL
    D33-1021365 2 ASL - D33DFAC STOCK 91G3920000081 CART, BIG WHEEL
    D33-1021425 5 ASL REORDER HAZMAT 91G8110000071 DRUM, PLASTIC
    D33-1020817 1 ASL REPLENISHMENT, D 91G5330002011 SEAL, THERMOSTAT
    D33-1022346 2 ASL STOCK REORDER E 92G6145000998 CABLE, POWER,
    D33-1022346 2 ASL STOCK REORDER E 92G6145000998 CABLE, POWER,
    D33-1020817 1 ASL REPLENISHMENT, D 91G5330002011 SEAL, THERMOSTAT
    D33-1020817 1 ASL REPLENISHMENT, D 91G5330002011 SEAL, THERMOSTAT
    D33-1022346 2 ASL STOCK REORDER E 92G6145000998 CABLE, POWER,
    but original we need..
    ponum polinenum maximo_tbl_a_po_description itemnum maximo_tbl_a_item_description
    D33-1021425 5 ASL REORDER HAZMAT 91G8110000071 DRUM, PLASTIC
    D33-1020817 2 ASL REPLENISHMENT, D 91G6685000371 THERMOSTAT
    D33-1021365 2 ASL - D33DFAC STOCK 91G3920000081 CART, BIG WHEEL
    D33-1020817 1 ASL REPLENISHMENT, D 91G5330002011 SEAL, THERMOSTAT
    D33-1022346 2 ASL STOCK REORDER E 92G6145000998 CABLE, POWER,

    Try below:
    SELECT DISTINCT
    maximo_tbl_matrectrans.ponum
    ,maximo_tbl_po.description AS [maximo_tbl_po description]
    ,maximo_tbl_matrectrans.polinenum
    ,maximo_tbl_matrectrans.itemnum
    ,maximo_tbl_item.description AS [maximo_tbl_item description]
    FROM
    maximo_tbl_matrectran
    INNER JOIN maximo_tbl_po
    ON maximo_tbl_matrectrans.ponum = maximo_tbl_po.ponum
    INNER JOIN maximo_tbl_item
    ON maximo_tbl_matrectrans.itemnum = maximo_tbl_item.itemnum
    -Vaibhav Chaudhari

  • Problem in Accession inner join with [Microsoft][SQLServer 2000 Driver

    Hi
    Can you tell me what can be cause my sql statement is correct gives result but
    if i used below statement in my JSP ,cause error
    1)
    ps1=connection.prepareStatement("select RQM_IN_RQSTN_ID_PK,RQD_IN_ITM_ID_FKPK,RQD_VC_ITM_DSCRPTN,RQD_IN_STTS_ID_FK,C.SMT_VC_STTS_NM,a.RQM_DT_PRPSD_DLVRY_DT"+
    "from PAS_RQM_RQSTN_MSTR a "+
    "inner join PAS_RQD_RQSTN_DTLS b on a.RQM_IN_RQSTN_ID_PK = b.RQD_IN_RQSTN_ID_FKPK and RQD_IN_STTS_ID_FK = 4"+
    "INNER JOIN PAS_SMT_STTS_MSTR C ON C.SMT_IN_STTS_ID_PK=B.RQD_IN_STTS_ID_FK" +
    "where a.RQM_VC_DTRTMNT_INVLV='Technology' ");
    2) Error Generate
    java.sql.SQLException
    [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Line 1: Incorrect syntax near 'a'.
    What can be the cause
    Thanks

    ps1=connection.prepareStatement("select
    RQM_IN_RQSTN_ID_PK,RQD_IN_ITM_ID_FKPK,RQD_VC_ITM_DSCRP
    TN,RQD_IN_STTS_ID_FK,C.SMT_VC_STTS_NM,a.RQM_DT_PRPSD_D
    LVRY_DT"+
    "from PAS_RQM_RQSTN_MSTR a "+
    "inner join PAS_RQD_RQSTN_DTLS b on
    a.RQM_IN_RQSTN_ID_PK = b.RQD_IN_RQSTN_ID_FKPK and
    RQD_IN_STTS_ID_FK = 4"+
    "INNER JOIN PAS_SMT_STTS_MSTR C ON
    C.SMT_IN_STTS_ID_PK=B.RQD_IN_STTS_ID_FK" +
    "where a.RQM_VC_DTRTMNT_INVLV='Technology' ");This is a problem due to not providing spaces where they are needed. See the places where I have highlighted.
    A better way is to generate the String first [use StringBuffer as a good practice for appending instead of String "+"] and print it out to check if it is correct.
    ***Annie***

  • Urgent help please.  Inner Join caused ora-00933 error

    I ran this one , works fine:
    SELECT DISTINCT EXP.EXP_ID,
    EXP.DATU_EXP_WIRE_CENTER_CLLI,
    EXP.DATU_EXP_IP,
    EXP.DATU_EXP_CLLI,
    EXP.DATU_EXP_PORT,
    EXP.DATU_EXP_NAME,
    EXP.DATU_EXP_CITY,
    EXP.DATU_EXP_STATE,
    EXP.DATU_EXP_SW_VERSION,
    DECODE(LAST_ALARM.LAST_ALARM_DATE, NULL, TO_CHAR(SYSDATE,'YYYY/MM/DD HH24:MI:SS'),
         TO_CHAR(LAST_ALARM.LAST_ALARM_DATE,'YYYY/MM/DD HH24:MI:SS')) AS STATUS_DATE,
    DECODE(LAST_ALARM.ALARM_NAME, NULL, 'Disconnected', LAST_ALARM.ALARM_NAME) AS DATU_STATUS,
    DECODE(LAST_ALARM.ALARM_CLASS, NULL, 'OTHER', LAST_ALARM.ALARM_CLASS) AS IS_ERROR_STATUS,
         DECODE(LAST_RESOURCE.LAST_ALARM_DATE, NULL, '', TO_CHAR(LAST_RESOURCE.LAST_ALARM_DATE,'YYYY/MM/DD HH24:MI:SS')) AS RESOURCE_STATUS_DATE,
         DECODE(LAST_RESOURCE.RESOURCE_CODE_NAME, NULL, '', LAST_RESOURCE.RESOURCE_CODE_NAME) AS RESOURCE_STATUS,
         DECODE(LAST_RESOURCE.RESOURCE_CODE_CLASS, NULL, '', LAST_RESOURCE.RESOURCE_CODE_CLASS) AS IS_RESOURCE_ERROR_STATUS,
         DECODE(LAST_OPER.LAST_ALARM_DATE, NULL, '', TO_CHAR(LAST_OPER.LAST_ALARM_DATE,'YYYY/MM/DD HH24:MI:SS')) AS OPER_STATUS_DATE,
         DECODE(LAST_OPER.OPER_CODE_NAME, NULL, '', LAST_OPER.OPER_CODE_NAME) AS OPER_STATUS,
         DECODE(LAST_OPER.OPER_CODE_CLASS, NULL, '', LAST_OPER.OPER_CODE_CLASS) AS IS_OPER_ERROR_STATUS,
    EXP.BEGIN_MAINT_WINDOW, RTU.RTU_NAME
    FROM TT_DATU_EXP_UNIT_INFO EXP
         left outer join
    ( SELECT distinct alarmed_datus.EXP_ID, c.ALARM_NAME, c.ALARM_TYPE, c.ALARM_CLASS, alarmed_datus.LAST_ALARM_DATE
    FROM ( SELECT EXP_ID, MAX(ALARM_TIME) AS LAST_ALARM_DATE FROM TT_DATU_EXP_ALARM_INFO GROUP BY EXP_ID ) alarmed_datus
    inner join TT_DATU_EXP_ALARM_INFO b on b.EXP_ID = alarmed_datus.EXP_ID AND b.ALARM_TIME = alarmed_datus.LAST_ALARM_DATE
    inner join TT_DATU_EXP_ALARM_TYPES c on b.ALARM_TYPE = c.ALARM_TYPE
    ) LAST_ALARM on EXP.EXP_ID = LAST_ALARM.EXP_ID
         left outer join
         ( SELECT distinct a.EXP_ID, c.RESOURCE_CODE_NAME, c.RESOURCE_CODE_TYPE, c.RESOURCE_CODE_CLASS, a.LAST_ALARM_DATE
         FROM ( SELECT EXP_ID, MAX(RESOURCE_CODE_TIME) AS LAST_ALARM_DATE
         FROM TT_DATU_EXP_RESOURCE_CODE_INFO GROUP BY EXP_ID ) a
    inner join TT_DATU_EXP_RESOURCE_CODE_INFO b on b.EXP_ID = a.EXP_ID AND b.RESOURCE_CODE_TIME = a.LAST_ALARM_DATE
    inner join TT_DATU_EXP_RESOURCECODE_TYPES c on b.RESOURCE_CODE_TYPE = c.RESOURCE_CODE_TYPE
         ) LAST_RESOURCE on EXP.EXP_ID = LAST_RESOURCE.EXP_ID
         left outer join
         ( SELECT distinct a.EXP_ID, c.OPER_CODE_NAME, c.OPER_CODE_TYPE, c.OPER_CODE_CLASS, a.LAST_ALARM_DATE
         FROM ( SELECT EXP_ID, MAX(OPER_CODE_TIME) AS LAST_ALARM_DATE
         FROM TT_DATU_EXP_OPER_CODE_INFO GROUP BY EXP_ID ) a
    inner join TT_DATU_EXP_OPER_CODE_INFO b on b.EXP_ID = a.EXP_ID AND b.OPER_CODE_TIME = a.LAST_ALARM_DATE
    inner join TT_DATU_EXP_OPER_CODE_TYPES c on b.OPER_CODE_TYPE = c.OPER_CODE_TYPE) LAST_OPER on EXP.EXP_ID = LAST_OPER.EXP_ID
    inner join TT_DATU_LRN_MAP LRNS on EXP.EXP_ID = LRNS.EXP_ID AND TRIM(LRNS.LRN) LIKE p_LRN
    inner join TT_RTU_TYPES RTU ON EXP.RTU_TYPE_ID = RTU.RTU_TYPE_ID
    WHERE NOT EXISTS (SELECT SATELLITE_EXP_ID FROM TT_HOST_SATELLITE WHERE EXP.EXP_ID = SATELLITE_EXP_ID)
    AND EXP.IS_PRIMARY_ADDRESS LIKE p_isPrimary;
         ELSE
         OPEN v_cursor FOR
    SELECT EXP.EXP_ID,
    EXP.DATU_EXP_WIRE_CENTER_CLLI,
    EXP.DATU_EXP_IP,
    EXP.DATU_EXP_CLLI,
    EXP.DATU_EXP_PORT,
    EXP.DATU_EXP_NAME,
    EXP.DATU_EXP_CITY,
    EXP.DATU_EXP_STATE,
    EXP.DATU_EXP_SW_VERSION,
    DECODE(LAST_ALARM.LAST_ALARM_DATE, NULL, TO_CHAR(SYSDATE,'YYYY/MM/DD HH24:MI:SS'), TO_CHAR(LAST_ALARM.LAST_ALARM_DATE,'YYYY/MM/DD HH24:MI:SS')) AS STATUS_DATE,
    DECODE(LAST_ALARM.ALARM_NAME, NULL, 'Disconnected', LAST_ALARM.ALARM_NAME) AS DATU_STATUS,
    DECODE(LAST_ALARM.ALARM_CLASS, NULL, 'OTHER', LAST_ALARM.ALARM_CLASS) AS IS_ERROR_STATUS,
         DECODE(LAST_RESOURCE.LAST_ALARM_DATE, NULL, '', TO_CHAR(LAST_RESOURCE.LAST_ALARM_DATE,'YYYY/MM/DD HH24:MI:SS')) AS RESOURCE_STATUS_DATE,
         DECODE(LAST_RESOURCE.RESOURCE_CODE_NAME, NULL, '', LAST_RESOURCE.RESOURCE_CODE_NAME) AS RESOURCE_STATUS,
         DECODE(LAST_RESOURCE.RESOURCE_CODE_CLASS, NULL, '', LAST_RESOURCE.RESOURCE_CODE_CLASS) AS IS_RESOURCE_ERROR_STATUS,
         DECODE(LAST_OPER.LAST_ALARM_DATE, NULL, '', TO_CHAR(LAST_OPER.LAST_ALARM_DATE,'YYYY/MM/DD HH24:MI:SS')) AS OPER_STATUS_DATE,
         DECODE(LAST_OPER.OPER_CODE_NAME, NULL, '', LAST_OPER.OPER_CODE_NAME) AS OPER_STATUS,
         DECODE(LAST_OPER.OPER_CODE_CLASS, NULL, '', LAST_OPER.OPER_CODE_CLASS) AS IS_OPER_ERROR_STATUS,
    EXP.BEGIN_MAINT_WINDOW, RTU.RTU_NAME
    FROM TT_DATU_EXP_UNIT_INFO EXP
         left outer join (
    SELECT distinct alarmed_datus.EXP_ID, c.ALARM_NAME, c.ALARM_TYPE, c.ALARM_CLASS, alarmed_datus.LAST_ALARM_DATE
    FROM (SELECT EXP_ID, MAX(ALARM_TIME) AS LAST_ALARM_DATE FROM TT_DATU_EXP_ALARM_INFO GROUP BY EXP_ID ) alarmed_datus
         inner join TT_DATU_EXP_ALARM_INFO b on b.EXP_ID = alarmed_datus.EXP_ID AND b.ALARM_TIME = alarmed_datus.LAST_ALARM_DATE
         inner join TT_DATU_EXP_ALARM_TYPES c on b.ALARM_TYPE = c.ALARM_TYPE )
         LAST_ALARM on EXP.EXP_ID = LAST_ALARM.EXP_ID
         left outer join
              ( SELECT distinct a.EXP_ID, c.RESOURCE_CODE_NAME, c.RESOURCE_CODE_TYPE, c.RESOURCE_CODE_CLASS, a.LAST_ALARM_DATE
              FROM ( SELECT EXP_ID, MAX(RESOURCE_CODE_TIME) AS LAST_ALARM_DATE
              FROM TT_DATU_EXP_RESOURCE_CODE_INFO GROUP BY EXP_ID ) a
         inner join TT_DATU_EXP_RESOURCE_CODE_INFO b on b.EXP_ID = a.EXP_ID AND b.RESOURCE_CODE_TIME = a.LAST_ALARM_DATE
         inner join TT_DATU_EXP_RESOURCECODE_TYPES c on b.RESOURCE_CODE_TYPE = c.RESOURCE_CODE_TYPE) LAST_RESOURCE on EXP.EXP_ID = LAST_RESOURCE.EXP_ID
         left outer join
              ( SELECT distinct a.EXP_ID, c.OPER_CODE_NAME, c.OPER_CODE_TYPE, c.OPER_CODE_CLASS, a.LAST_ALARM_DATE
              FROM ( SELECT EXP_ID, MAX(OPER_CODE_TIME) AS LAST_ALARM_DATE
              FROM TT_DATU_EXP_OPER_CODE_INFO GROUP BY EXP_ID ) a
         inner join TT_DATU_EXP_OPER_CODE_INFO b on b.EXP_ID = a.EXP_ID AND b.OPER_CODE_TIME = a.LAST_ALARM_DATE
         inner join TT_DATU_EXP_OPER_CODE_TYPES c on b.OPER_CODE_TYPE = c.OPER_CODE_TYPE
              ) LAST_OPER on EXP.EXP_ID = LAST_OPER.EXP_ID ORDER BY EXP.DATU_EXP_CLLI
         inner join TT_RTU_TYPES RTU ON EXP.RTU_TYPE_ID = RTU.RTU_TYPE_ID
    WHERE NOT EXISTS (SELECT SATELLITE_EXP_ID FROM TT_HOST_SATELLITE WHERE EXP.EXP_ID = SATELLITE_EXP_ID) AND EXP.IS_PRIMARY_ADDRESS like
    p_isPrimary;
    However this one:
    SELECT EXP.EXP_ID,
    EXP.DATU_EXP_WIRE_CENTER_CLLI,
    EXP.DATU_EXP_IP,
    EXP.DATU_EXP_CLLI,
    EXP.DATU_EXP_PORT,
    EXP.DATU_EXP_NAME,
    EXP.DATU_EXP_CITY,
    EXP.DATU_EXP_STATE,
    EXP.DATU_EXP_SW_VERSION,
    DECODE(LAST_ALARM.LAST_ALARM_DATE, NULL, TO_CHAR(SYSDATE,'YYYY/MM/DD HH24:MI:SS'),
         TO_CHAR(LAST_ALARM.LAST_ALARM_DATE,'YYYY/MM/DD HH24:MI:SS')) AS STATUS_DATE,
    DECODE(LAST_ALARM.ALARM_NAME, NULL, 'Disconnected', LAST_ALARM.ALARM_NAME) AS DATU_STATUS,
    DECODE(LAST_ALARM.ALARM_CLASS, NULL, 'OTHER', LAST_ALARM.ALARM_CLASS) AS IS_ERROR_STATUS,
         DECODE(LAST_RESOURCE.LAST_ALARM_DATE, NULL, '', TO_CHAR(LAST_RESOURCE.LAST_ALARM_DATE,'YYYY/MM/DD HH24:MI:SS')) AS RESOURCE_STATUS_DATE,
         DECODE(LAST_RESOURCE.RESOURCE_CODE_NAME, NULL, '', LAST_RESOURCE.RESOURCE_CODE_NAME) AS RESOURCE_STATUS,
         DECODE(LAST_RESOURCE.RESOURCE_CODE_CLASS, NULL, '', LAST_RESOURCE.RESOURCE_CODE_CLASS) AS IS_RESOURCE_ERROR_STATUS,
         DECODE(LAST_OPER.LAST_ALARM_DATE, NULL, '', TO_CHAR(LAST_OPER.LAST_ALARM_DATE,'YYYY/MM/DD HH24:MI:SS')) AS OPER_STATUS_DATE,
         DECODE(LAST_OPER.OPER_CODE_NAME, NULL, '', LAST_OPER.OPER_CODE_NAME) AS OPER_STATUS,
         DECODE(LAST_OPER.OPER_CODE_CLASS, NULL, '', LAST_OPER.OPER_CODE_CLASS) AS IS_OPER_ERROR_STATUS,
    EXP.BEGIN_MAINT_WINDOW, RTU.RTU_NAME
    FROM TT_DATU_EXP_UNIT_INFO EXP
         left outer join
    SELECT distinct alarmed_datus.EXP_ID, c.ALARM_NAME, c.ALARM_TYPE, c.ALARM_CLASS, alarmed_datus.LAST_ALARM_DATE
    FROM ( SELECT EXP_ID, MAX(ALARM_TIME) AS LAST_ALARM_DATE FROM TT_DATU_EXP_ALARM_INFO GROUP BY EXP_ID) alarmed_datus
         inner join TT_DATU_EXP_ALARM_INFO b on b.EXP_ID = alarmed_datus.EXP_ID AND b.ALARM_TIME = alarmed_datus.LAST_ALARM_DATE
         inner join TT_DATU_EXP_ALARM_TYPES c on b.ALARM_TYPE = c.ALARM_TYPE ) LAST_ALARM on EXP.EXP_ID = LAST_ALARM.EXP_ID
         left outer join
              ( SELECT distinct a.EXP_ID, c.RESOURCE_CODE_NAME, c.RESOURCE_CODE_TYPE, c.RESOURCE_CODE_CLASS, a.LAST_ALARM_DATE
              FROM ( SELECT EXP_ID, MAX(RESOURCE_CODE_TIME) AS LAST_ALARM_DATE
              FROM TT_DATU_EXP_RESOURCE_CODE_INFO GROUP BY EXP_ID ) a
         inner join TT_DATU_EXP_RESOURCE_CODE_INFO b on b.EXP_ID = a.EXP_ID AND b.RESOURCE_CODE_TIME = a.LAST_ALARM_DATE
         inner join TT_DATU_EXP_RESOURCECODE_TYPES c on b.RESOURCE_CODE_TYPE = c.RESOURCE_CODE_TYPE) LAST_RESOURCE on EXP.EXP_ID = LAST_RESOURCE.EXP_ID
         left outer join
              ( SELECT distinct a.EXP_ID, c.OPER_CODE_NAME, c.OPER_CODE_TYPE, c.OPER_CODE_CLASS, a.LAST_ALARM_DATE
              FROM ( SELECT EXP_ID, MAX(OPER_CODE_TIME) AS LAST_ALARM_DATE
              FROM TT_DATU_EXP_OPER_CODE_INFO GROUP BY EXP_ID ) a
         inner join TT_DATU_EXP_OPER_CODE_INFO b on b.EXP_ID = a.EXP_ID AND b.OPER_CODE_TIME = a.LAST_ALARM_DATE
         inner join TT_DATU_EXP_OPER_CODE_TYPES c on b.OPER_CODE_TYPE = c.OPER_CODE_TYPE
              ) LAST_OPER on EXP.EXP_ID = LAST_OPER.EXP_ID ORDER BY EXP.DATU_EXP_CLLI
    inner join TT_RTU_TYPES RTU ON EXP.RTU_TYPE_ID = RTU.RTU_TYPE_ID
    WHERE EXP.IS_PRIMARY_ADDRESS like p_isPrimary;
    this one not work kept giving me errors:
    [ ORA-00933: SQL command not properly ended
    Any guru can help? I need to have this resolved end of today.
    Thanks in advance.

    Hi,
    Never write, let alone post, unformatted code.
    Indent the code so that it's easy to set the scope of sub-queries, and the majoc clauses (SELECT, FROM, WHERE, ORDER BY, ...) in each.
    When posting any formatted text on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    If you do that to the code you posted, you'll see that it ends like this:... inner join     TT_DATU_EXP_OPER_CODE_INFO     b on b.EXP_ID     = a.EXP_ID
                                       AND      b.OPER_CODE_TIME = a.LAST_ALARM_DATE
         inner join      TT_DATU_EXP_OPER_CODE_TYPES      c on      b.OPER_CODE_TYPE = c.OPER_CODE_TYPE
         ) LAST_OPER          on EXP.EXP_ID = LAST_OPER.EXP_ID
    ORDER BY EXP.DATU_EXP_CLLI
    inner join TT_RTU_TYPES RTU     ON EXP.RTU_TYPE_ID = RTU.RTU_TYPE_ID
    WHERE EXP.IS_PRIMARY_ADDRESS      like p_isPrimary
    You can't put an ORDER BY clause  in the middle of the FROM clause.
    The ORDER BY clause always goes after the WHERE clause, like this:... inner join     TT_DATU_EXP_OPER_CODE_INFO     b on b.EXP_ID     = a.EXP_ID
                                       AND      b.OPER_CODE_TIME = a.LAST_ALARM_DATE
         inner join      TT_DATU_EXP_OPER_CODE_TYPES      c on      b.OPER_CODE_TYPE = c.OPER_CODE_TYPE
         ) LAST_OPER          on EXP.EXP_ID = LAST_OPER.EXP_ID
    inner join TT_RTU_TYPES RTU     ON EXP.RTU_TYPE_ID = RTU.RTU_TYPE_ID
    WHERE EXP.IS_PRIMARY_ADDRESS      like p_isPrimary
    ORDER BY EXP.DATU_EXP_CLLI

  • Dynamic Table name in Inner Join in  4.6c

    data: tab1(10) type c value 'MARA',
            tab2(10) type c value 'MAKT'.
    data: dbtab1(10) type c,
             dbtab2(10) type c .
    dbtab1 = tab1. 
    dbtab2 = tab2. 
    DATA: BEGIN OF itab occurs 0,
               matnr TYPE mara-matnr,
               maktx type makt-maktx,
    END OF itab.
    DATA: column_syntax TYPE string,
                dbtab_syntax TYPE string.
    PARAMETERS: p_matnr TYPE mara-matnr.
    dbtab_syntax = '( (dbtab1) AS t1 '
    &' INNER JOIN (dbtab2) AS t4 ON t1MATNR = t4MATNR )'.
    SELECT  matnr maktx
    FROM (dbtab_syntax)
    INTO TABLE itab  WHERE t4~matnr   = p_matnr.
    Got the following error:
    "A table name, specified in an SQL command, is unknown"
    It seems not able to read dynamic table name in dbtab_syntax.
    thanks
    anya
    Moderation Message: Duplicate Post.
    Edited by: kishan P on Nov 29, 2010 11:17 AM

    Hi,
    Check this link.
    [http://help.sap.com/saphelp_nw04/helpdata/en/fc/eb39c4358411d1829f0000e829fbfe/frameset.htm]
    [Re: accessing dynamic internal table's fields??;
    hope it'll help u.
    Regards,
    Sneha.
    Edited by: sneha kumari on Jun 18, 2009 1:57 PM

  • ORA-00947 Error on straight SELECT with INNER JOINs

    I have a REAL bizarre situation. I have a SQL SELECT Statement that is joining a few tables. I actually have a WHERE clause where I am filtering by a coulmn within one of the joins. However, if I try to SELECT that coulmn, I am getting an Oracle error ORA-00947. I can even SELECT * and get ALL the columns back form ALL the tables I'm joing on, including the one that is not allowing me just to select it.
    Has anyone ever seen anything like this before???
    I appreciate your review and am hopeful for a reply.
    Thanks.
    PSULionRP

    Jez....Not sure if I need to worry about proprietary stuff here...Here's the SQL and the column I'm trying to select is CDM_SUPPLIER_UTILITY.SUPPLIER_CD.
    When I do that is when I get the ORA-00947 error. And our version is...
    Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
    SELECT CDM_CALENDAR.CALENDAR_DT,
    CDM_OFFER.SUPPLIER_NAME,
    CDM_SUPPLIER_UTILITY.SUPPLIER_CD,
    ABS(SUM(CDM_MONEY.TRANSACTION_AMT))
    FROM CDEDM.CDM_TRANSACTIONS CDM_TRANSACTIONS
    INNER JOIN CDEDM.CDM_MONEY CDM_MONEY
    ON CDM_MONEY.TRANSACTION_FK = CDM_TRANSACTIONS.TRANSACTION_GK_PK
    INNER JOIN CDEDM.CDM_OFFER CDM_OFFER
    ON CDM_OFFER.OFFER_GK_PK = CDM_MONEY.OFFER_FK
    INNER JOIN CDEDM.CDM_CALENDAR CDM_CALENDAR
    ON CDM_CALENDAR.CALENDAR_DT_PK = CDM_MONEY.TRANSACTION_DT_FK
    INNER JOIN CDEDM.CDM_BILL_ACCOUNTS CDM_BILL_ACCOUNTS
    ON CDM_BILL_ACCOUNTS.BILL_ACCT_GK_PK = CDM_MONEY.BILL_ACCOUNTS_FK
    INNER JOIN CDEDM.CDM_SUPPLIER_UTILITY CDM_SUPPLIER_UTILITY
    ON CDM_SUPPLIER_UTILITY.SUPPLIER_UTILITY_GK_PK = CDM_BILL_ACCOUNTS.SUPPLIER_FK
    WHERE CDM_SUPPLIER_UTILITY.SUPPLIER_CD = 'MC2'
    AND CDM_CALENDAR.CALENDAR_DT BETWEEN NEXT_DAY(trunc(SYSDATE-12),'Saturday')
    AND NEXT_DAY(trunc(SYSDATE-5),'Saturday')
    AND CDM_TRANSACTIONS.TRAN_DECODE IN
    'Debit/Bill Installment Billing',
    'Debit/Bill Electric Service',
    'Debit by Transfer of Payment TO Uncollec',
    'Debit Miscellaneous Electric',
    'Credit for Transfer TO Uncollectible',
    'Credit for Tranfer FROM Uncollectible',
    'Credit Miscellaneous Electric',
    'Credit Alteration',
    'Credit Allowance',
    'Bill Consumption On An Inactive Meter'
    AND CDM_MONEY.TRANSACTION_LEVEL_CD IN
    'A',
    GROUP BY CDM_CALENDAR.CALENDAR_DT,
    CDM_OFFER.SUPPLIER_NAME,
    CDM_SUPPLIER_UTILITY.SUPPLIER_CD

  • Very Slow Query with CTE inner join

    I have 2 tables (heavily simplified here to show relevant columns):
    CREATE TABLE tblCharge
    (ChargeID int NOT NULL,
    ParentChargeID int NULL,
    ChargeName varchar(200) NULL)
    CREATE TABLE tblChargeShare
    (ChargeShareID int NOT NULL,
    ChargeID int NOT NULL,
    TotalAmount money NOT NULL,
    TaxAmount money NULL,
    DiscountAmount money NULL,
    CustomerID int NOT NULL,
    ChargeShareStatusID int NOT NULL)
    I have a very basic View to Join them:
    CREATE VIEW vwBASEChargeShareRelation as
    Select c.ChargeID, ParentChargeID, s.CustomerID, s.TotalAmount, isnull(s.TaxAmount, 0) as TaxAmount, isnull(s.DiscountAmount, 0) as DiscountAmount
    from tblCharge c inner join tblChargeShare s
    on c.ChargeID = s.ChargeID Where s.ChargeShareStatusID < 3
    GO
    I then have a view containing a CTE to get the children of the Parent Charge:
    ALTER VIEW [vwChargeShareSubCharges] AS
    WITH RCTE AS
    SELECT ParentChargeId, ChargeID, 1 AS Lvl, ISNULL(TotalAmount, 0) as TotalAmount, ISNULL(TaxAmount, 0) as TaxAmount,
    ISNULL(DiscountAmount, 0) as DiscountAmount, CustomerID, ChargeID as MasterChargeID
    FROM vwBASEChargeShareRelation Where ParentChargeID is NULL
    UNION ALL
    SELECT rh.ParentChargeID, rh.ChargeID, Lvl+1 AS Lvl, ISNULL(rh.TotalAmount, 0), ISNULL(rh.TaxAmount, 0), ISNULL(rh.DiscountAmount, 0) , rh.CustomerID
    , rc.MasterChargeID
    FROM vwBASEChargeShareRelation rh
    INNER JOIN RCTE rc ON rh.PArentChargeID = rc.ChargeID and rh.CustomerID = rc.CustomerID
    Select MasterChargeID as ChargeID, CustomerID, Sum(TotalAmount) as TotalCharged, Sum(TaxAmount) as TotalTax, Sum(DiscountAmount) as TotalDiscount
    from RCTE
    Group by MasterChargeID, CustomerID
    GO
    So far so good, I can query this view and get the total cost for a line item including all children.
    The problem occurs when I join this table. The query:
    Select t.* from vwChargeShareSubCharges t
    inner join
    tblChargeShare s
    on t.CustomerID = s.CustomerID
    and t.MasterChargeID = s.ChargeID
    Where s.ChargeID = 1291094
    Takes around 30 ms to return a result (tblCharge and Charge Share have around 3.5 million records).
    But the query:
    Select t.* from vwChargeShareSubCharges t
    inner join
    tblChargeShare s
    on t.CustomerID = s.CustomerID
    and t.MasterChargeID = s.ChargeID
    Where InvoiceID = 1045854
    Takes around 2 minutes to return a result - even though the only charge with that InvoiceID is the same charge as the one used in the previous query.
    The same thing occurs if I do the join in the same query that the CTE is defined in.
    I ran the execution plan for each query. The first (fast) query looks like this:
    The second(slow) query looks like this:
    I am at a loss, and my skills at decoding execution plans to resolve this are lacking.
    I have separate indexes on tblCharge.ChargeID, tblCharge.ParentChargeID, tblChargeShare.ChargeID, tblChargeShare.InvoiceID, tblChargeShare.ChargeShareStatusID
    Any ideas? Tested on SQL 2008R2 and SQL 2012

    >> The database is linked [sic] to an established app and the column and table names can't be changed. <<
    Link? That is a term from pointer chains and network databases, not SQL. I will guess that means the app came back in the old pre-RDBMS days and you are screwed. 
    >> I am not too worried about the money field [sic], this is used for money and money based calculations so the precision and rounding are acceptable at this level. <<
    Field is a COBOL concept; columns are totally different. MONEY is how Sybase mimics the PICTURE clause that puts currency signs, commas, period, etc in a COBOL money field. 
    Using more than one operation (multiplication or division) on money columns will produce severe rounding errors. A simple way to visualize money arithmetic is to place a ROUND() function calls after 
    every operation. For example,
    Amount = (Portion / total_amt) * gross_amt
    can be rewritten using money arithmetic as:
    Amount = ROUND(ROUND(Portion/total_amt, 4) * 
    gross_amt, 4)
    Rounding to four decimal places might not seem an 
    issue, until the numbers you are using are greater 
    than 10,000. 
    BEGIN
    DECLARE @gross_amt MONEY,
     @total_amt MONEY,
     @my_part MONEY,
     @money_result MONEY,
     @float_result FLOAT,
     @all_floats FLOAT;
     SET @gross_amt = 55294.72;
     SET @total_amt = 7328.75;
     SET @my_part = 1793.33;
     SET @money_result = (@my_part / @total_amt) * 
    @gross_amt;
     SET @float_result = (@my_part / @total_amt) * 
    @gross_amt;
     SET @Retult3 = (CAST(@my_part AS FLOAT)
     / CAST( @total_amt AS FLOAT))
     * CAST(FLOAT, @gross_amt AS FLOAT);
     SELECT @money_result, @float_result, @all_floats;
    END;
    @money_result = 13525.09 -- incorrect
    @float_result = 13525.0885 -- incorrect
    @all_floats = 13530.5038673171 -- correct, with a -
    5.42 error 
    >> The keys are ChargeID(int, identity) and ChargeShareID(int, identity). <<
    Sorry, but IDENTITY is not relational and cannot be a key by definition. But it sure works just like a record number in your old COBOL file system. 
    >> .. these need to be int so that they are assigned by the database and unique. <<
    No, the data type of a key is not determined by physical storage, but by logical design. IDENTITY is the number of a parking space in a garage; a VIN is how you identify the automobile. 
    >> What would you recommend I use as keys? <<
    I do not know. I have no specs and without that, I cannot pull a Kabbalah number from the hardware. Your magic numbers can identify Squids, Automobile or Lady Gaga! I would ask the accounting department how they identify a charge. 
    >> Charge_Share_Status_ID links [sic] to another table which contains the name, formatting [sic] and other information [sic] or a charge share's status, so it is both an Id and a status. <<
    More pointer chains! Formatting? Unh? In RDBMS, we use a tiered architecture. That means display formatting is in a presentation layer. A properly created table has cohesion – it does one and only one data element. A status is a state of being that applies
    to an entity over a period time (think employment, marriage, etc. status if that is too abstract). 
    An identifier is based on the Law of Identity from formal logic “To be is to be something in particular” or “A is A” informally. There is no entity here! The Charge_Share_Status table should have the encoded values for a status and perhaps a description if
    they are unclear. If the list of values is clear, short and static, then use a CHECK() constraint. 
    On a scale from 1 to 10, what color is your favorite letter of the alphabet? Yes, this is literally that silly and wrong. 
    >> I understand what a CTE is; is there a better way to sum all children for a parent hierarchy? <<
    There are many ways to represent a tree or hierarchy in SQL.  This is called an adjacency list model and it looks like this:
    CREATE TABLE OrgChart 
    (emp_name CHAR(10) NOT NULL PRIMARY KEY, 
     boss_emp_name CHAR(10) REFERENCES OrgChart(emp_name), 
     salary_amt DECIMAL(6,2) DEFAULT 100.00 NOT NULL,
     << horrible cycle constraints >>);
    OrgChart 
    emp_name  boss_emp_name  salary_amt 
    ==============================
    'Albert'    NULL    1000.00
    'Bert'    'Albert'   900.00
    'Chuck'   'Albert'   900.00
    'Donna'   'Chuck'    800.00
    'Eddie'   'Chuck'    700.00
    'Fred'    'Chuck'    600.00
    This approach will wind up with really ugly code -- CTEs hiding recursive procedures, horrible cycle prevention code, etc.  The root of your problem is not knowing that rows are not records, that SQL uses sets and trying to fake pointer chains with some
    vague, magical non-relational "id".  
    This matches the way we did it in old file systems with pointer chains.  Non-RDBMS programmers are comfortable with it because it looks familiar -- it looks like records and not rows.  
    Another way of representing trees is to show them as nested sets. 
    Since SQL is a set oriented language, this is a better model than the usual adjacency list approach you see in most text books. Let us define a simple OrgChart table like this.
    CREATE TABLE OrgChart 
    (emp_name CHAR(10) NOT NULL PRIMARY KEY, 
     lft INTEGER NOT NULL UNIQUE CHECK (lft > 0), 
     rgt INTEGER NOT NULL UNIQUE CHECK (rgt > 1),
      CONSTRAINT order_okay CHECK (lft < rgt));
    OrgChart 
    emp_name         lft rgt 
    ======================
    'Albert'      1   12 
    'Bert'        2    3 
    'Chuck'       4   11 
    'Donna'       5    6 
    'Eddie'       7    8 
    'Fred'        9   10 
    The (lft, rgt) pairs are like tags in a mark-up language, or parens in algebra, BEGIN-END blocks in Algol-family programming languages, etc. -- they bracket a sub-set.  This is a set-oriented approach to trees in a set-oriented language. 
    The organizational chart would look like this as a directed graph:
                Albert (1, 12)
        Bert (2, 3)    Chuck (4, 11)
                       /    |   \
                     /      |     \
                   /        |       \
                 /          |         \
            Donna (5, 6) Eddie (7, 8) Fred (9, 10)
    The adjacency list table is denormalized in several ways. We are modeling both the Personnel and the Organizational chart in one table. But for the sake of saving space, pretend that the names are job titles and that we have another table which describes the
    Personnel that hold those positions.
    Another problem with the adjacency list model is that the boss_emp_name and employee columns are the same kind of thing (i.e. identifiers of personnel), and therefore should be shown in only one column in a normalized table.  To prove that this is not
    normalized, assume that "Chuck" changes his name to "Charles"; you have to change his name in both columns and several places. The defining characteristic of a normalized table is that you have one fact, one place, one time.
    The final problem is that the adjacency list model does not model subordination. Authority flows downhill in a hierarchy, but If I fire Chuck, I disconnect all of his subordinates from Albert. There are situations (i.e. water pipes) where this is true, but
    that is not the expected situation in this case.
    To show a tree as nested sets, replace the nodes with ovals, and then nest subordinate ovals inside each other. The root will be the largest oval and will contain every other node.  The leaf nodes will be the innermost ovals with nothing else inside them
    and the nesting will show the hierarchical relationship. The (lft, rgt) columns (I cannot use the reserved words LEFT and RIGHT in SQL) are what show the nesting. This is like XML, HTML or parentheses. 
    At this point, the boss_emp_name column is both redundant and denormalized, so it can be dropped. Also, note that the tree structure can be kept in one table and all the information about a node can be put in a second table and they can be joined on employee
    number for queries.
    To convert the graph into a nested sets model think of a little worm crawling along the tree. The worm starts at the top, the root, makes a complete trip around the tree. When he comes to a node, he puts a number in the cell on the side that he is visiting
    and increments his counter.  Each node will get two numbers, one of the right side and one for the left. Computer Science majors will recognize this as a modified preorder tree traversal algorithm. Finally, drop the unneeded OrgChart.boss_emp_name column
    which used to represent the edges of a graph.
    This has some predictable results that we can use for building queries.  The root is always (left = 1, right = 2 * (SELECT COUNT(*) FROM TreeTable)); leaf nodes always have (left + 1 = right); subtrees are defined by the BETWEEN predicate; etc. Here are
    two common queries which can be used to build others:
    1. An employee and all their Supervisors, no matter how deep the tree.
     SELECT O2.*
       FROM OrgChart AS O1, OrgChart AS O2
      WHERE O1.lft BETWEEN O2.lft AND O2.rgt
        AND O1.emp_name = :in_emp_name;
    2. The employee and all their subordinates. There is a nice symmetry here.
     SELECT O1.*
       FROM OrgChart AS O1, OrgChart AS O2
      WHERE O1.lft BETWEEN O2.lft AND O2.rgt
        AND O2.emp_name = :in_emp_name;
    3. Add a GROUP BY and aggregate functions to these basic queries and you have hierarchical reports. For example, the total salaries which each employee controls:
     SELECT O2.emp_name, SUM(S1.salary_amt)
       FROM OrgChart AS O1, OrgChart AS O2,
            Salaries AS S1
      WHERE O1.lft BETWEEN O2.lft AND O2.rgt
        AND S1.emp_name = O2.emp_name 
       GROUP BY O2.emp_name;
    4. To find the level and the size of the subtree rooted at each emp_name, so you can print the tree as an indented listing. 
    SELECT O1.emp_name, 
       SUM(CASE WHEN O2.lft BETWEEN O1.lft AND O1.rgt 
       THEN O2.sale_amt ELSE 0.00 END) AS sale_amt_tot,
       SUM(CASE WHEN O2.lft BETWEEN O1.lft AND O1.rgt 
       THEN 1 ELSE 0 END) AS subtree_size,
       SUM(CASE WHEN O1.lft BETWEEN O2.lft AND O2.rgt
       THEN 1 ELSE 0 END) AS lvl
      FROM OrgChart AS O1, OrgChart AS O2
     GROUP BY O1.emp_name;
    5. The nested set model has an implied ordering of siblings which the adjacency list model does not. To insert a new node, G1, under part G.  We can insert one node at a time like this:
    BEGIN ATOMIC
    DECLARE rightmost_spread INTEGER;
    SET rightmost_spread 
        = (SELECT rgt 
             FROM Frammis 
            WHERE part = 'G');
    UPDATE Frammis
       SET lft = CASE WHEN lft > rightmost_spread
                      THEN lft + 2
                      ELSE lft END,
           rgt = CASE WHEN rgt >= rightmost_spread
                      THEN rgt + 2
                      ELSE rgt END
     WHERE rgt >= rightmost_spread;
     INSERT INTO Frammis (part, lft, rgt)
     VALUES ('G1', rightmost_spread, (rightmost_spread + 1));
     COMMIT WORK;
    END;
    The idea is to spread the (lft, rgt) numbers after the youngest child of the parent, G in this case, over by two to make room for the new addition, G1.  This procedure will add the new node to the rightmost child position, which helps to preserve the idea
    of an age order among the siblings.
    6. To convert a nested sets model into an adjacency list model:
    SELECT B.emp_name AS boss_emp_name, E.emp_name
      FROM OrgChart AS E
           LEFT OUTER JOIN
           OrgChart AS B
           ON B.lft
              = (SELECT MAX(lft)
                   FROM OrgChart AS S
                  WHERE E.lft > S.lft
                    AND E.lft < S.rgt);
    7. To find the immediate parent of a node: 
    SELECT MAX(P2.lft), MIN(P2.rgt)
      FROM Personnel AS P1, Personnel AS P2
     WHERE P1.lft BETWEEN P2.lft AND P2.rgt 
       AND P1.emp_name = @my_emp_name;
    I have a book on TREES & HIERARCHIES IN SQL which you can get at Amazon.com right now. It has a lot of other programming idioms for nested sets, like levels, structural comparisons, re-arrangement procedures, etc. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Issue when suming the field in Select query using inner join

    Hi All,
    SELECT A~OI_SHNUM
           A~FORWAGENT        
           A~ROUTE
           A~SHTYP
           A~DTSHP_EACT
           A~/BIC/GTCLICENS
           A~/BIC/GTCADD04
           A~COMP_CODE
           SUM( C~GRS_WGT_DL )
           C~UNIT_OF_WT
      INTO TABLE I_LAYONE
      FROM ( ( /BIC/ANTCD000200 AS A
      INNER JOIN /BIC/AGSSD000700 AS B ON BOI_SHNUM = AOI_SHNUM )
      INNER JOIN /BIC/AGSSD000600 AS C ON CDELIV_NUMB = BDELIV_NUMB ).
    I need to sum the field C~GRS_WGT_DL
    While compiling it show the error given below
    The field "C~UNIT_OF_WT" from the SELECT list is is missing in the
    GROUP BY clause. is missing in the GROUP BY clause. is missing in the
    GROUP BY clause. is missing in the GROUP BY clause. is missing in the
    GROUP BY clause. is "C~UNIT_OF_W
    with regards,
    Thambe

    Hi,
    Try the following SQL statement. Hope it helps you.
    SELECT A~OI_SHNUM
    A~FORWAGENT
    A~ROUTE
    A~SHTYP
    A~DTSHP_EACT
    A~/BIC/GTCLICENS
    A~/BIC/GTCADD04
    A~COMP_CODE
    SUM( C~GRS_WGT_DL )
    C~UNIT_OF_WT
    INTO TABLE I_LAYONE
    FROM ( ( /BIC/ANTCD000200 AS A
    INNER JOIN /BIC/AGSSD000700 AS B ON BOI_SHNUM = AOI_SHNUM )
    INNER JOIN /BIC/AGSSD000600 AS C ON CDELIV_NUMB = BDELIV_NUMB )
    GROUP BY
    A~OI_SHNUM
    A~FORWAGENT
    A~ROUTE
    A~SHTYP
    A~DTSHP_EACT
    A~/BIC/GTCLICENS
    A~/BIC/GTCADD04
    A~COMP_CODE.
    Murthy.

  • Inner Join in oracle 10g

    Is it possible to use inner join in oracle 10g?

    SQL> select ename, dname
      2  from emp inner join dept
      3  on emp.deptno=dept.deptno;
    ENAME      DNAME
    SMITH      RESEARCH
    ALLEN      SALES
    WARD       SALES
    JONES      RESEARCH
    MARTIN     SALES
    BLAKE      SALES
    CLARK      ACCOUNTING
    SCOTT      RESEARCH
    KING       ACCOUNTING
    TURNER     SALES
    ADAMS      RESEARCH
    ENAME      DNAME
    JAMES      SALES
    FORD       RESEARCH
    MILLER     ACCOUNTING
    14 rows selected.
    SQL>

Maybe you are looking for