Query 4 joined tables with internal joins to represent a complex hierarchy!

I've got to refine/replace a query (Oracle 9i) that
currently joins rows from four tables in a hierarchical
fashion that I use to produce a listing like this:
agency abc 1
....division def 1.1
........service ghi 1.1.1
........service jkl 1.1.2
............faq mno 1.1.2.1
............faq pqr 1.1.2.2
........service stu 1.1.3
....division vwx 1.2
........service yyy 1.2.1
............faq zzz 1.2.1.1
The change involves allowing for unlimited levels of
nested child divisions to produce a listing like this:
agency abc 1
....division def 1.1
........service ghi 1.1.1
........service jkl 1.1.2
............faq mno 1.1.2.1
............faq pqr 1.1.2.2
........service stu 1.1.3
....division vwx 1.2
........division xxx 1.2.1
............division aaa 1.2.1.1
............division bbb 1.2.1.2
................service aaa 1.2.1.2.1
....................faq fff 1.2.1.2.1.1
....................faq ggg 1.2.1.2.1.2
........service yyy 1.2.1
............faq zzz 1.2.1.1
Notice the insertion of three nested divisions under
division 1.2 with services and faqs under those. The
order of names throughout is alphabetic within a nesting
level.
Here's the SQL I currently use, without nested divisions
(it contains extra info that I use to control what and
how names are displayed):
SELECT
agency.agency_id AGENCY_ID,
agency.agency_type_id AGENCY_TYPE_ID,
agency.name AGENCY_NAME,
agency.acronym AGENCY_ACRONYM,
agency.expiration_date AGENCY_EXP,
agency.post_count AGENCY_POST,
agency.stat AGENCY_STAT,
agency_type.agency_type AGENCY_TYPE,
division.division_id DIV_ID,
division.name DIV_NAME,
division.transfer_number DIV_TRANS_NUM,
division.expiration_date DIV_EXP,
division.post_count DIV_POST,
division.stat DIV_STAT,
service.service_id SVC_ID,
service.name SVC_NAME,
service.taxonomy SVC_TAX,
service.keywords SVC_KEYWORDS,
service.action_type SVC_ACTION_TYPE,
service.sr_form_name SVC_SR_FORM,
service.expiration_date SVC_EXP,
service.post_count SVC_POST,
service.stat SVC_STAT,
faq.faq_id FAQ_ID,
faq.name FAQ_NAME,
faq.expiration_date FAQ_EXP,
faq.post_count FAQ_POST,
faq.stat FAQ_STAT
FROM
agency,
agency_type,
division left join service on
division.division_id=service.division_id left join
faq on service.service_id=faq.service_id
WHERE (
(agency_type.agency_type_id = agency.agency_type_id)
AND (agency.agency_id = division.agency_id)
AND (agency.agency_id = :agency_id )
It's very fast -- I can retrieve and display 5,000 rows
in seconds using Perl DBI and CGI -- and very easy to use
to produce the hierarchical listing of items from the
four tables. It is also very straightforward since I was
able to generate the SQL using the SQL modeler in TOAD
(I'm not the strongest SQL developer so I resort to
tools).
I need to get jump-started in the right direction to
determine what I need to add to my division table
(div_parent_id?), if I need a div_parent_child table to
define the relationships (rows with parent_id & child_id
pairs), and how to change or rewrite the SQL query. The
CGI form that will be used to define the relationships
will ask users to define children of a given division. I
envision presenting a list of divisions with null
parent_division_id columns for users to select from then
updating selected rows for selected divsions.
Thanks in advance for any help/guidance!
-Gene

INLINE VIEWS!
select whatever_you_want
from (
SELECT FOLDER_ID, PARENT_FOLDER_ID, FOLDER_NAME
FROM FOLDERS
START WITH PARENT_FOLDER_ID = 0 CONNECT BY PARENT_FOLDER_ID = PRIOR FOLDER_ID
) tree, FILES
where tree.folder_id = files.folder_id -- or something like that
always try to keep the CONNECT BY limited to ONE AND ONLY table. then use that query in a subquery, a WITH clause, an inline view or something. do not try to JOIN or UNION with a CONNECT BY. it won't work the way you think it will, and even it returns the expected results, it will perform terribly.
* your mileage may vary
Message was edited by:
shoblock
added exclamation marks to show my excitement!!!!

Similar Messages

  • Join table with additional data

    Hi,
    I'm new to JPA (Toplink Essentials) and I'd like to know how to handle this situation:
    I have ORDER table, ITEMS table and "join table" ORDER_ITEMS which holds refernces to ordered items with quantity of each oredered item.
    Many thanks

    I did mapping as shown in listing. It works for reading, but for writing JPA returns error. Can somebody help?
    Thanks
    [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Column name 'idexpedice' appears more than once in the result column list.
    Error Code: 264
    Call: INSERT INTO vklad_expedice (IDEXPEDICE, IDVKLAD, VAHA, idexpedice, idvklad) VALUES (?, ?, ?, ?, ?)
    bind => [null, null, 0, 4411, 2]
    @Entity
    public class Expedice implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer idexpedice;
    @Temporal(TemporalType.DATE)
    private Date datum;
    @OneToMany(fetch = FetchType.EAGER, mappedBy="expedice", cascade = CascadeType.ALL)
    private List<ExpediceVklad> vklady;
    @Entity
    public class Vklad implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer idvklad;
    private String nazev;
    @Entity
    @Table(name = "vklad_expedice")
    @IdClass(ExpediceVkladId.class)
    public class ExpediceVklad implements Serializable {
    @Id
    private Integer idexpedice;
    @Id
    private Integer idvklad;
    private Integer vaha;
    @ManyToOne
    @JoinColumn(name = "idexpedice")
    private Expedice expedice;
    @ManyToOne
    @JoinColumn(name = "idvklad")
    private Vklad vklad;
    public class ExpediceVkladId {
    @Id
    private Integer idexpedice;
    @Id
    private Integer idvklad;
    SQL tables
    EXPEDICE
    idexpedice
    datum
    VKLAD
    idvklad
    nazev
    VKLAD_EXPEDICE (this is the join table with additional column)
    idexpedice
    idvklad
    vaha
    Edited by: user10933983 on 31.3.2009 13:47

  • ORA-00604 ORA-00904 When query partitioned table with partitioned indexes

    Got ORA-00604 ORA-00904 When query partitioned table with partitioned indexes in the data warehouse environment.
    Query runs fine when query the partitioned table without partitioned indexes.
    Here is the query.
    SELECT al2.vdc_name, al7.model_series_name, COUNT (DISTINCT (al1.vin)),
    al27.accessory_code
    FROM vlc.veh_vdc_accessorization_fact al1,
    vlc.vdc_dim al2,
    vlc.model_attribute_dim al7,
    vlc.ppo_list_dim al18,
    vlc.ppo_list_indiv_type_dim al23,
    vlc.accy_type_dim al27
    WHERE ( al2.vdc_id = al1.vdc_location_id
    AND al7.model_attribute_id = al1.model_attribute_id
    AND al18.mydppolist_id = al1.ppo_list_id
    AND al23.mydppolist_id = al18.mydppolist_id
    AND al23.mydaccytyp_id = al27.mydaccytyp_id
    AND ( al7.model_series_name IN ('SCION TC', 'SCION XA', 'SCION XB')
    AND al2.vdc_name IN
    ('PORT OF BALTIMORE',
    'PORT OF JACKSONVILLE - LEXUS',
    'PORT OF LONG BEACH',
    'PORT OF NEWARK',
    'PORT OF PORTLAND'
    AND al27.accessory_code IN ('42', '43', '44', '45')
    GROUP BY al2.vdc_name, al7.model_series_name, al27.accessory_code

    I would recommend that you post this at the following OTN forum:
    Database - General
    General Database Discussions
    and perhaps at:
    Oracle Warehouse Builder
    Warehouse Builder
    The Oracle OLAP forum typically does not cover general data warehousing topics.

  • 3 tables with left joins - bug?

    Hello,
    i am making query where i encounter problem with left join in oracle. I am using oracle 10g and i prepare simple test case.
    he is testing tables and datas - really simple i think:
    drop table t1;
    drop table t2;
    drop table t3;
    create table t1 (a number not null);
    create table t2 (a number, b number);
    create table t3 (b number);
    insert into t3 values (1);
    insert into t3 values (2);
    insert into t3 values (3);
    insert into t1 (a) values (1);
    insert into t2 (a,b) values (1,1);
    insert into t1 (a) values (2);
    insert into t2 (a,b) values (2, null);
    insert into t1 (a) values (3);
    insert into t1 (a) values (4);
    insert into t2 (a,b) values (4,1);
    insert into t1 (a) values (5);
    insert into t2 (a,b) values (5,3);
    and now query with left joins:
    select
    t1.a
    , t2.a, t2.b
    , t3.b
    from
    t1, t2, t3
    where
    t1.a = t2.a (+)
    and t2.b = t3.b (+)
    and t3.b is null
    order by t1.a
    i get two rows as result:
    A A_1 B B_1
    2 2 null null      
    3 null null null                
    i expect these rows but when i change my query - i dont want get back t3.b column:
    select
    t1.a
    , t2.a, t2.b
    /* , t3.b*/
    from
    t1, t2, t3
    where
    t1.a = t2.a (+)
    and t2.b = t3.b (+)
    and t3.b is null
    order by t1.a
    i get only one row
    A A_1 B
    2 2 null
    My question is simple how can i only by changing columns getting back change number of returned rows? I must say i dont expect these result i expect two rows again.
    Thanks for help.

    BluShadow wrote:
    I think I know what you are getting at.
    By testing for null on t3.b when you aren't selecting the column, you are enforcing oracle to perform the join through t2 onto t1, but Oracle can't join because t2 has no matching row (although it's outer joined to t1) and therefore, for the one row it can't actually determine if t3.b is null or not, so that row can't match the conditions in a "true" sense and be displayed. If you select the column then oracle can test its nullness ok. (Perhaps this is a bug, I don't know, it's just how I know it works)If you get different results only by changing the projection part of the query this is a bug and nothing else. I can't reproduce using Oracle 10g XE, I get in both cases shown the expected two rows.
    What versions are you using to test this?
    SQL>
    SQL> select * from v$version
      2  where rownum <= 1;
    BANNER
    Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
    SQL>
    SQL> drop table t1 purge;
    Table dropped.
    SQL> drop table t2 purge;
    Table dropped.
    SQL> drop table t3 purge;
    Table dropped.
    SQL>
    SQL> create table t1 (a number not null);
    Table created.
    SQL> create table t2 (a number, b number);
    Table created.
    SQL> create table t3 (b number);
    Table created.
    SQL>
    SQL> insert into t3 values (1);
    1 row created.
    SQL> insert into t3 values (2);
    1 row created.
    SQL> insert into t3 values (3);
    1 row created.
    SQL>
    SQL> insert into t1 (a) values (1);
    1 row created.
    SQL> insert into t2 (a,b) values (1,1);
    1 row created.
    SQL>
    SQL> insert into t1 (a) values (2);
    1 row created.
    SQL> insert into t2 (a,b) values (2, null);
    1 row created.
    SQL>
    SQL> insert into t1 (a) values (3);
    1 row created.
    SQL>
    SQL> insert into t1 (a) values (4);
    1 row created.
    SQL> insert into t2 (a,b) values (4,1);
    1 row created.
    SQL>
    SQL> insert into t1 (a) values (5);
    1 row created.
    SQL> insert into t2 (a,b) values (5,3);
    1 row created.
    SQL>
    SQL> commit;
    Commit complete.
    SQL>
    SQL> select t1.a
      2       , t2.a, t2.b
      3       , t3.b
      4  from
      5         t1 left outer join t2 on (t1.a = t2.a)
      6            left outer join t3 on (t2.b = t3.b)
      7  where t3.b is null
      8  order by t1.a;
             A          A          B          B
             2          2
             3
    SQL>
    SQL> select t1.a
      2       , t2.a, t2.b
      3  --     , t3.b
      4  from
      5         t1 left outer join t2 on (t1.a = t2.a)
      6            left outer join t3 on (t2.b = t3.b)
      7  where t3.b is null
      8  order by t1.a;
             A          A          B
             2          2
             3
    SQL>Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • Can we join table with structure

    Hi
    i have taken fields from Plaf table and some fields from structures so now i want to join that how can i join.
    Is there any option?
    regards

    Hi,
    structure dont have any data base table associated with them so they dont have any data.
    that's why we cannot join structure witha table but we can include a structure within any table.
    Sytex to include structure in ztable:
    fieldname     data element.
    .include        struname
    hope it will ans ur query.
    Thanks
    Rajesh Kumar

  • How to use common object from two tables with out join.

    HI,
    I have two tables called A & B In A table i have the following objects
    1.weekend
    2.S1(measure)
    3.S2(measure)
    4.S3(measure)
    5.S4(measure)
    And In B table i have followning columns
    1.week end
    2.p1(measure)
    3.p2(measure)
    4.p3(measure)
    5.p4(measure)
    Now in universe i created all the measure objects i.e.s1,s2,s3,s4,p1,p2,p3,p4 A.weekend,B.weekend.
    instead of using week end two times i wnt to use only once because this is common in both table.
    if i use join between these tables i am getting values fine
    But With out join is there any thing to do in universe level to create common objects to use from both the tables..I tried using aggregate awareness but while reporting it is taking as two SQL.which is not synchronized.
    Please help me on this ...

    hi,
    Although  Weekend column is present in both tables, by creating a single Object in Universe, Universe can identify relationship with only table referenced in Object Creation.
    So, there will be no identification of relationship with other table measures.
    Obviously, you need to create 2 Weekend objects in Universe (in two classes).
    Case 1: You need not join these two tables in Universe. When you create 2 Queries in WEBI, automatcially Weekend objects are synchronized (if both are of same datatype)
    Case 2: If you join these two tables in Universe, Obviously,
    your SQL may contain Weekend from Table1, measures from Table 2
    or
    your SQL may contain Weekend from Table2, measures from Table 1
    Finally, You need to create 2 objects in Universe. But your query may contain a single Object based on Case 2.
    Regards,
    Vamsee

  • Join table with an object type

    Hi,
    I would like ot know how to join a table with another table having an object type as a column value.
    For ex:
    Create type add_obj as object (st varchar2(10), city varchar2(10), zip varchar2(10));
    Table A
    Cust_id number
    cust_address add_obj
    Table B
    Cust_id number
    order_id number
    I want to select the complete address for each order.
    Is this the correct way to do this select:
    Select o.order_id, c.customer_id, c.cust_address.st, c.cust_address.city, c.cust_address.zip
    from table A c, table B o;
    Any leads is appreciated. Thanks in advance.

    >
    unfortunately with a crashed Oracle db I could try nothing.... Forums are for getting help and offering help in times of need.
    Will take your advice some other time. Now need help on how to select the address city, st and zip along with the order_id.
    >
    Ah - I understand - you mean before your class is over.
    Unfortunately with a crashed Oracle db you will not know if our advice is correct or not since you won't be able to test it.
    So I will offer advice some other time. Now need to get some fresh air and a hot cup of coffee.
    Let us know when you DB is back up and you have run your tests. Then if you still have any questions other forum members may decide to help you. Well - if their database is up and running that is.

  • Many to many join table with different column names

    Hi have a joint table with different column names as foreign keys in the joining
    tables...
    e.g. i have a many to many reltnshp btwn Table A and Table B ..and join table
    C
    both have a column called pk.
    and the join table C has columns call fk1 and fk2
    does cmd require the same column name in the join table as in the joining table?
    are there any workarounds?
    thanks

    HI,
    No, the foreign key column names in the join table do not have to match the primary
    key names in the joined tables.
    -thorick

  • Joining tables with SQL in Crystal XI

    I am new to Crsytal Reports. I want to join 2 tables using a formula, which I am trying to do in SQL. I created a simple test report and I can get it to work if I don't put any fields on the report from the joined table.  ie  -  if I just use fields from "sal-rep" the report works.  As soon as I add a field from "freight" (my joined table) the report will not display anything.  (but I don't get any error messages - just a blank report).  Here is my SQL: 
    SELECT "sal-rep"."full-name","sal-rep"."invoice-nbr","freight"."misc-charge-ammount"  FROM   "PUB"."sal-rep" INNER JOIN "PUB"."FREIGHT" ON ("sal-rep"."invoice-nbr"="freight"."invoice-nbr")  WHERE  "sal-rep"."invoice-nbr"='0000189957'

    I got it to work!!!   This is the SQL I used -
    SELECT "sal_rep"."full-name", "sal_rep"."invoice-nbr", "freight"."misc-charge-ammount", "freight"."invoice-date"
    FROM   "PUB"."freight" "freight" INNER JOIN "PUB"."sal-rep" "sal_rep" ON ("freight"."invoice-nbr"="sal_rep"."invoice-nbr") AND ("freight"."invoice-date"="sal_rep"."inv-date")
    WHERE  "sal_rep"."invoice-nbr"='0000189957'
    Now when I look at the Table used in Database expert it lists -  Command and Freight.
    Before it was listing Command and Sal-Rep. 
    Not sure I understand why, but at least it's working.
    thanks for your help - really appreciated!

  • Updating parent row in a self-join table with triggers

    Hi Gurus!
    Need of a business to update parent row(s) in the same table with triggers (insert, update and delete). Table is having recursive relation and error is coming as mutating error. I was able to do this with MS-SQL server.
    Appreciate any help or work around possibilities.
    Regards,
    SH

    SH,
    popular solutions to this issue include
    - autonomous transactions
    - recording (typically in PL/SQL package variables) the rows being processed from the row level triggers and using this information in the after statement level trigger to perform the update on the parent rows
    - use a View with an instead of trigger to re-route the DML on your table
    Which one to use depends on what exactly you are trying to achieve and how the data hangs together.
    Lucas

  • How do i join 3 table with the 'join' query ?

    Hello,
    i want to join 3 tables -> bsis, bsad and vbrp
    the components of the query to be are ,
    - select (matnr from vbrp) sum(amount from bsad).
    - join bsis and bsad on  bsisbukrs = bsadbukrs, bsisbelnr = bsadaugbl and bsisbldat = bsadaugdt.
    - where bsisblart = 'DZ' and bsishkont = '123456'.
    - join bsad and vbrp on vbrpburks = bsadbukrs, vbrpgjahr = bsadgjahr and vbrpbelnr = bsadbelnr.
    The double join query is to be constructed out of the above components.
    Thanks,
    Shehryar Dahar

    c an example....
    DATA: BEGIN OF wa,
            carrid TYPE spfli-carrid,
            connid TYPE spfli-connid,
            fldate TYPE sflight-fldate,
            bookid TYPE sbook-bookid,
          END OF wa,
          itab LIKE SORTED TABLE OF wa
                    WITH UNIQUE KEY carrid connid fldate bookid.
    SELECT  pcarrid pconnid ffldate bbookid
      INTO  CORRESPONDING FIELDS OF TABLE itab
      FROM  ( ( spfli AS p
                INNER JOIN sflight AS f ON pcarrid = fcarrid AND
                                           pconnid = fconnid    )
                INNER JOIN sbook   AS b ON bcarrid = fcarrid AND
                                           bconnid = fconnid AND
                                           bfldate = ffldate     )
      WHERE p~cityfrom = 'FRANKFURT' AND
            p~cityto   = 'NEW YORK'  AND
            fseatsmax > fseatsocc.
    LOOP AT itab INTO wa.
      AT NEW fldate.
        WRITE: / wa-carrid, wa-connid, wa-fldate.
      ENDAT.
      WRITE / wa-bookid.
    ENDLOOP.
    Ramesh.

  • How to delete a row from a SQL Server CE Table with multiple JOINs?

    I want to delete a record from a SQL Server CE table.
    There are 3 tables scripts, options and results. I would like to remove a record from the results table. The where clause contains dynamic information which retrieved via other queries to different tables in the same database. These queries work fine and deliver
    the desired data.
    The Compact server is a clone of a remote table created using the sync framework. The same query to the remote table works fine.
    The error I get is:
    There was an error parsing the query. [ Token line number = 1,Token line offset = 10,Token in error = from ]
    The code that throws the exception is as follows:
    Dim connLoc As SqlCeConnection = New SqlCeConnection(My.Settings.ConnectionString)connLoc.Open()     Dim strDel As String = "Delete r from ResultsTable r inner join OptionsTable o ON o.TestName=r.TestName inner join ScriptTable c ON r.TestName=c.TestName WHERE r.TestName = '" & ds1Loc.Tables(0).Rows(0)(1) & "' AND [Index] = '" & lstIndex & "'"Dim cmdDel As SqlCeCommand = New SqlCeCommandcmdDel.CommandText = strDelcmdDel.Connection = connLoccmdDel.ExecuteNonQuery()
    The values held in ds1Loc.Tables(0).Rows(0)(1) and lstIndex are
    correct so should not be the problem.
    I also tried using parameterised queries
    Dim strDel As String = "Delete r from [ResultsTable] r inner join [OptionsTable] o ON o.TestName=r.TestName inner join [ScriptTable] c ON r.TestName=c.TestName WHERE r.TestName = @TestName AND [Index] = @lstIndex"
    Dim cmdDel As SqlCeCommand = New SqlCeCommand        cmdDel.CommandText = strDel       
    With cmdDel.Parameters           
    .Add(New SqlCeParameter("@TestName", ds1Loc.Tables(0).Rows(0)(1)))           
    .Add(New SqlCeParameter("@lstIndex", lstIndex))       
    End With 
    cmdDel.Connection = connLoc        cmdDel.ExecuteNonQuery()
    I have tried replacing the "=" with "IN" in the the WHERE clause but this has not worked.
    Is it the join that is causing the problem? I can do a select with the same search criteria and joins from the same database.
    Also this query works with SQL Server. Is it perhaps that SQL CE does not support the Delete function the same as SQL Server 2008? I have been looking at this for a while now and cannot find the source of the error. Any help would be greatly appreciated.

    Hello,
    In SQL Server Compact, we can use join in FROM clause. The DELETE statement fail may be caused by the FOREIGN KEY constraint.
    Please refer to:
    DELETE (SQL Server Compact)
    FROM Clause (SQL Server Compact)
    Regards,
    Fanny Liu
    Fanny Liu
    TechNet Community Support

  • How to refresh a table with multiple joins

    Hi,
    First at all, I'm newby in ADF, and my english is no so good, sorry for that...
    I'm using JDeveloper 11g Release 2 (11.1.2.3.0). I have a table created from a view object that have multiple joins with other entities. When I insert a new row programmatically in one of the entities of the joins (not in the entitiy of the view object itself), the new row is created in the database correctly but the table don't show it. What can I do to refresh the table to see the new row created?
    Thanks in advance!

    You have to update the iterator the table is based on for the ui last. You do that by executing the query on the iterator again.
    Timo

  • How can i join table with multiple colums

    This is my Data-----------------------------------------------------DECLARE @StockIn TABLE
    InID INT ,
    StockID INT ,
    InQty DECIMAL(16, 2) ,
    Price DECIMAL(16, 2) ,
    tranDate DATE ,
    running INT
    DECLARE @StockOut TABLE
    OutID INT ,
    StockID INT ,
    OutQty DECIMAL(16, 2) ,
    lineid INT ,
    tranDate DATE
    INSERT INTO @StockIn ( InID, StockID, InQty, Price, tranDate, running )
    VALUES ( 1, 1, 15, 430, '2014-10-09', 1 ),
    ( 2, 1, 10, 431, '2014-10-10', 2 ),
    ( 3, 1, 15, 432, '2015-02-02', 3 ),
    ( 4, 2, 15, 450, '2014-08-05', 1 ),
    ( 5, 2, 6, 450, '2014-10-01', 2 ),
    ( 6, 2, 15, 452, '2015-10-02', 3 )
    INSERT INTO @StockOut ( OutID, StockID, OutQty, lineid, tranDate )
    VALUES ( 1, 1, 20, 2, '2014-10-11' ),
    ( 2, 1, 10, 4, '2014-10-12' ),
    ( 3, 2, 12, 8, '2014-11-01' ),
    ( 4, 2, 3, 8, '2014-11-02' );--------------------------------------------------------------------This is my query for calculate the total remaining of stock of any stockID--------------------------------------------------------------------                    WITH  RunningTotals as (
    select StockID , Qty , price , total , total - qty AS PrevTotal, TranDate , rn FROM (
    select 
     StockID, InQty  AS QTY , Price 
    , SUM(InQty) over (PARTITION BY StockID order by tranDate ,  inQty DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Total
    ,ROW_NUMBER() OVER (PARTITION BY StockID ORDER BY  tranDate ,  inQty DESC ) as rn
    ,TranDate --,TranID, TxnType
    from @StockIn  )  A   -- runing stockID in stock order by tranDate
    ) , TotalOut as ( 
    SELECT    StockID ,  Sum(OutQty) AS QTY
    FROM            @StockOut 
       GROUP BY StockID  -- Sum of outQty group by StockID
    ) ,  GrandTotal as 
    select
    rt.StockID , rt.QTY AS original ,SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty, 0) END) AS QTY , Price , SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty, 0) END * Price) AS Ending , rt.TranDate  from 
    RunningTotals rt
    left join
    TotalOut out
    on
    rt.StockID = out.StockID 
    where rt.Total > isNull(out.Qty , 0)
    group by rt.StockID , Price , rt.TranDate  , rt.QTY  -- running OutQty out of inQty of any stockID
    ) Select * from GrandTotal order by stockID ------------------------------------------------------------
    This query is run the total remaining of stock exactly right. But if i try to get the OutQty of stockID of any Line (lineid)The query duplicate data. this is Example------------------------------------------------------------                    DECLARE @StockIn TABLE
          InID INT ,
          StockID INT ,
          InQty DECIMAL(16, 2) ,
          Price DECIMAL(16, 2) ,
          tranDate DATE ,
          running INT
    DECLARE @StockOut TABLE
          OutID INT ,
          StockID INT ,
          OutQty DECIMAL(16, 2) ,
          lineid INT ,
          tranDate DATE
    INSERT  INTO @StockIn ( InID, StockID, InQty, Price, tranDate, running )
    VALUES  ( 1, 1, 15, 430, '2014-10-09', 1 ),
            ( 2, 1, 10, 431, '2014-10-10', 2 ),
            ( 3, 1, 15, 432, '2015-02-02', 3 ),
            ( 4, 2, 15, 450, '2014-08-05', 1 ),
            ( 5, 2, 6, 450, '2014-10-01', 2 ),
            ( 6, 2, 15, 452, '2015-10-02', 3 )
    INSERT  INTO @StockOut ( OutID, StockID, OutQty, lineid, tranDate )
    VALUES  ( 1, 1, 20, 2, '2014-10-11' ),
            ( 2, 1, 10, 4, '2014-10-12' ),
            ( 3, 2, 12, 8, '2014-11-01' ),
            ( 4, 2, 3, 8, '2014-11-02' );
    WITH  RunningTotals as (
    select StockID , Qty , price , total , total - qty AS PrevTotal, TranDate , rn FROM (
    select 
     StockID, InQty  AS QTY , Price 
    , SUM(InQty) over (PARTITION BY StockID order by tranDate ,  inQty DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Total
    ,ROW_NUMBER() OVER (PARTITION BY StockID ORDER BY  tranDate ,  inQty DESC ) as rn
    ,TranDate --,TranID, TxnType
    from @StockIn  )  A  
    ) , TotalOut as ( 
    SELECT    StockID ,  Sum(OutQty) AS QTY , lineid -- Group by stockID of any lineidFROM            @StockOut 
       GROUP BY StockID   , lineid
    ) ,  GrandTotal as 
    select
    rt.StockID , rt.QTY AS original ,SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty, 0) END) AS QTY , Price , SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty, 0) END * Price) AS Ending , rt.TranDate , lineid from 
    RunningTotals rt
    left join
    TotalOut out
    on
    rt.StockID = out.StockID 
    where rt.Total > isNull(out.Qty , 0)
    group by rt.StockID , Price , rt.TranDate  , rt.QTY   , lineid
    ) Select * from GrandTotal order by stockID ----------------------------------------------How can i running the total out (OutQty*price) of any lineid

    Check this query, the date is excluded because it cannot return the result you want with and it will not be of any value to read the date like that in such a query:
    DECLARE @StockIn TABLE
    InID INT ,
    StockID INT ,
    InQty DECIMAL(16, 2) ,
    Price DECIMAL(16, 2) ,
    tranDate DATE ,
    running INT
    DECLARE @StockOut TABLE
    OutID INT ,
    StockID INT ,
    OutQty DECIMAL(16, 2) ,
    lineid INT ,
    tranDate DATE
    INSERT INTO @StockIn ( InID, StockID, InQty, Price, tranDate, running )
    VALUES ( 1, 1, 15, 430, '2014-10-09', 1 ),
    ( 2, 1, 10, 431, '2014-10-10', 2 ),
    ( 3, 1, 15, 432, '2015-02-02', 3 ),
    ( 4, 2, 15, 450, '2014-08-05', 1 ),
    ( 5, 2, 6, 450, '2014-10-01', 2 ),
    ( 6, 2, 15, 452, '2015-10-02', 3 )
    INSERT INTO @StockOut ( OutID, StockID, OutQty, lineid, tranDate )
    VALUES ( 1, 1, 20, 2, '2014-10-11' ),
    ( 2, 1, 10, 4, '2014-10-12' ),
    ( 3, 2, 12, 8, '2014-11-01' ),
    ( 4, 2, 3, 8, '2014-11-02' );
    WITH RunningTotals as (
    select StockID , Qty , price , total , total - qty AS PrevTotal, TranDate , rn FROM (
    select
    StockID, InQty AS QTY , Price
    , SUM(InQty) over (PARTITION BY StockID order by tranDate , inQty DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Total
    ,ROW_NUMBER() OVER (PARTITION BY StockID ORDER BY tranDate , inQty DESC ) as rn
    ,TranDate --,TranID, TxnType
    from @StockIn ) A
    ) , TotalOut as (
    SELECT StockID , Sum(OutQty) AS QTY , lineid -- Group by stockID of any lineid
    FROM @StockOut
    GROUP BY StockID , lineid
    ) , GrandTotal as
    select
    rt.StockID , rt.QTY AS original ,SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty, 0) END) AS QTY , Price , SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty, 0) END * Price) AS Ending , rt.TranDate , lineid from
    RunningTotals rt
    left join
    TotalOut out
    on
    rt.StockID = out.StockID
    where rt.Total > isNull(out.Qty , 0)
    group by rt.StockID , Price , rt.TranDate , rt.QTY , lineid
    ) Select Distinct StockID,(select sum(original) from GrandTotal G where G.lineid = GrandTotal.lineid) as original,(select sum(QTY) from GrandTotal G where G.lineid = GrandTotal.lineid) as QTY,
    (select sum(Price) from GrandTotal G where G.lineid = GrandTotal.lineid) as Price, (select sum(Ending) from GrandTotal G where G.lineid = GrandTotal.lineid) as Ending,lineid from GrandTotal
    order by stockID
    the result will be:
    StockID original QTY Price Ending lineid
    1 25.00 20.00 863.00 8635.0000 2
    1 40.00 30.00 1293.00 12940.0000 4
    2 21.00 21.00 902.00 9480.0000 8
    Fouad Roumieh

  • VPD problem: select for update on join tables with policy on ref table

    In our application we use VPD. Now we ran into an issue. I will try to explain with EMP and DEPT table.
    EMP table has no VPD attached.
    DEPT table has VPD policy that forbids all updates, but allows select. (Policy returns '1=2' for statement type update.
    This query returns no rows:
    select * from emp join dept using (department_id) for update. This makes sense, because I'm going to update both the tables.
    However:
    select * from emp join dept using (department_id) for update of employee_id also returns no rows. THIS IS WRONG. I'm not going to update dept table.
    Any experience with this. Is this a known limitation ?

    I can see all the rows, because there is no select policy.
    However the point is, that VPD should allow me to update the emp table, because there is no update policy.
    With the 'for update of employee_id' clause, VPD should recognize that I'm not going to update the dept table, but only the emp table. But VPD does not recognize this, but applies the update policy of dept to the statement, making the statement to update no rows.
    (Reason behind my question is ADF Business Components, where you have ViewObjects with Referenced Entities. ADF BC generates this type of statement and now we run into this VDP limitation)

Maybe you are looking for

  • Difference between Key feilds and Data fileds in ODS

    Hi team, What is diff between data fields and Key fileds in ODS ?. Pl let me know. Regards, Senthil

  • Best practice for data persistance for monitoring without BAM

    Greetings, We are modeling a business process in a large organization using BPEL Process Manager. The key point is that business people needs to monitor the execution of the business process in several key sectors of the process execution as well as

  • Booklet printing in InDesign 5

    How do I print a specific spread from booklet printing in InDesign 5?

  • Structured Document Template Issues

    Hi, I have been given a set of files (EDD, DTD, Template)  which I am meant to use to create some manuals. I can create an XML file ok but when I try to open the XML file I get a lot of error messages saying they cannot create the elements. I have di

  • Master detail DML

    Hi, I am using ADF and JSF . I have a master detail screen and in the header part, it shows 10 records at a time. In the detail part, there is an insert button for users to create new records. Clicking the insert button goes to a new page. After ente