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!

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

  • How can I load data into table with SQL*LOADER

    how can I load data into table with SQL*LOADER
    when column data length more than 255 bytes?
    when column exceed 255 ,data can not be insert into table by SQL*LOADER
    CREATE TABLE A (
    A VARCHAR2 ( 10 ) ,
    B VARCHAR2 ( 10 ) ,
    C VARCHAR2 ( 10 ) ,
    E VARCHAR2 ( 2000 ) );
    control file:
    load data
    append into table A
    fields terminated by X'09'
    (A , B , C , E )
    SQL*LOADER command:
    sqlldr test/test control=A_ctl.txt data=A.xls log=b.log
    datafile:
    column E is more than 255bytes
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)
    1     1     1     1234567------(more than 255bytes)

    Check this out.
    http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96652/ch06.htm#1006961

  • How to Create a Temporary Table with SQL Server

    I know you can create a temporary table in SQL Server 2000, but not quite sure how to do it in CFMX 7, i.e., does the SQL go inside a <CFQUERY dbtype="query"> tag?
    I'm pulling the main set of records from an Oracle server (1st data source), but it does not contain employee names, only employee IDs.  Since I need to show the employee name along with the Emp ID, I'm then pulling a list of "current" employee names from a SQL Server (2nd data source), which is the main database on our CF server.
    I've got a QofQ that works fine, except it only matches EmpIDs that exist in both result sets.  Employees who are no longer employed, don't match, and don't display.  Since I can't do a LEFT OUTER JOIN with a QofQ, what I need to do is get the records from the Oracle server into the SQL Server.  Preferably in a temporary table.
    I was hoping if I could get those Oracle records written to a temp table on the main SQL Server, in same database as the Employee Name table, I could then write a normal <CFQUERY> that uses a LEFT OUTER JOIN.
    I think I could probably write a Stored Procedure that would execute the SQL to create the temporary table, but am trying to avoid having to write the SP, and do it the simplest way.
    This query will be a program that can be run hundreds of times per day, with a form that allows users to select date ranges, locations, and other options.  That starts the queries, which creates the report.  So I just need the temp table to exist only until all the SQL has run, and the <CFOUTPUT> has generated a report.
    If the premise is right, I just need some help with the syntax for creating a SQL Server temp table, when you want to write records to it from an external data source.  I'm trying the following, but getting an error:
    <CFQUERY name="ITE_Temp" datasource="SkynetSQL">
    CREATE TABLE #MyTemp
    (   INSERT INTO #MyTemp
    ITE2.TrueFile char (7) NOT NULL,
    ITE2.CountOfEmployee int NULL,
    ITE2.DTL_SUBTOT decimal NULL,
    ITE2.EMPTYPE char (3) NULL,
    ITE2.ARPT_CD char (3) NULL
    </CFQUERY>
    So I actually created a permanent table on the SQL Server, and wrote the below SQL, which does work, and does write the records to table.  I can then write another CFQUERY with a LEFT OUTER JOIN, and get all the records, including those that don't have matching employee name:
    <CFQUERY datasource="SkynetSQL">
    <CFLOOP index="i" from="1" to = "#ITE2.RecordCount#">
    INSERT INTO ITE_Temp
       (FullFile,
       EmployeeCount,
       DTL_Amount,
       EmployeeType,
       station)
    VALUES  ('#ITE2.TrueFile[i]#',
       #ITE2.CountOfEmployee[i]#,
       #ITE2.DTL_SUBTOT[i]#,
       '#ITE2.EMPTYPE[i]#',
       '#ITE2.ARPT_CD[i]#')
    </CFLOOP>
    </CFQUERY>
    But, I hate to have to create a table and physically write to it.  For one, it seems slower, and doing it in temp would be in memory, and probably much faster, correct?  Is there some way to code the above, so that it does something similar, but in a TEMPORARY TABLE?   If I can figure out how to do this, I can pull data from multiple data sources and servers, and using SQL Server temp tables, work with the data as if it was all on the same SQL Server, and do some cool reports.
    Everything I've done for the past few years, has all been from data from a single source, whether SQL Server, or another server.  Now I need to start writing reports where data can come from 3 or 4 different servers, and be able to do joins (inner and outer).  Thanks for any advice/help.  Much appreciated.
    Gary

    While waiting to hear back, I was able to write the query results from an outside Oracle server, to a table on the local SQL Server, and do the LEFT OUTER JOIN required for the final query and report to work.  That was with this syntax:
    <CFQUERY name="AddTableRecords" datasource="MyTable">
    TRUNCATE TABLE ITE_Temp
    <CFOUTPUT query="ITE2">
    INSERT INTO ITE_Temp
    (FullFile,EmployeeCount,DTL_Amount,EmployeeType,station)
    VALUES
    ('#TrueFile#', #CountOfEmployee#, #DTL_SUBTOT#, '#EMPTYPE#', '#ARPT_CD#')
    </CFOUTPUT>
    </CFQUERY>
    However, I was not able to write to a temporary table AND read the results. I got the syntax to run to write the above results to a temporary table.  But when I tried to read and output the results from the temp table, I got an error.  Also, it wouldn't take the single "#" (local) only the global "##" table var, using this syntax.  Note that if I didn't have the DROP TABLE in the beginning, the 2nd time you run this query, you get an error telling you the table already exists.
    <CFQUERY name="ITE_Temp2" datasource="MyTable">
    DROP TABLE ##MyTemp2
    CREATE TABLE ##MyTemp2
    FullFile char (7) NOT NULL,
    EmployeeCount int NULL,
    DTL_Amount decimal NULL,
    EmployeeType char (3) NULL,
    station char (3) NULL
    <CFOUTPUT query="ITE2">
    INSERT INTO ##MyTemp2 VALUES
    '#ITE2.TrueFile#',
    #ITE2.CountOfEmployee#,
    #ITE2.DTL_SUBTOT#,
    '#ITE2.EMPTYPE#',
    '#ITE2.ARPT_CD#'
    </CFOUTPUT>
    </CFQUERY>
    So even though the above works, I could use some help in reading/writing the output.  I've tried several things similar to below, but they don't work.  It't telling me ITE_Temp2 does not exist.  It's not easy to find good examples of creating temporary tables in SQL Server.
    <CFQUERY name="QueryTest2" datasource="SkynetSQL">
    SELECT *
    FROM ITE_Temp2
    </CFQUERY>
    <CFOUTPUT query="ITE_Temp2">
    Output from Temp Table<br>
    <p>FullFile: #FullFile#, EmployeeCount: #EmployeeCount#</p>
    </CFOUTPUT>
    Thanks for any help/advice.
    Gary.

  • 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

  • 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

  • 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

  • Loading multiple tables with SQL Loader

    Hi,
    I want to load multiple tables from a single data file using SQL Loader.
    Here's the basic idea of what I want. Let's say I have two tables, table =T1
    and table T2:
    SQL> desc T1;
    COL1 VARCHAR2(20)
    COL2 VARCHAR2(20)
    SQL> desc T2;
    COL1 VARCHAR2(20)
    COL2 VARCHAR2(20)
    COL3 VARCHAR2(20)
    My data file, test.dat, looks like this:
    AAA|KBA
    BBR|BBCC|CCC
    NNN|BBBN|NNA
    I want to load the first record into T1, and the second and third record load into T2. How do I set up my control file to do that?
    Thank!

    Tough Job
    LOAD DATA
    truncate
    INTO table t1
    when col3 = 'dummy'
    FIELDS TERMINATED BY '|'
    TRAILING NULLCOLS
    (col1,col2,col3 filler char nullif col3='dummy')
    INTO table t2
    when col3 != 'dummy'
    FIELDS TERMINATED BY '|'
    (col1,col2,col3 nullif col3='dummy')
    This will load t2 tbl but not t1.
    T1 Filler col3 is not accepting nullif. Its diff to compare columns have null using when condition. If i find something i will let you know.
    Can you seperate records into 2 file. Will a UNIX command work for you which will seperate 2col and 3col record types for you. and then you can execute 2 controlfiles on it.
    Thanks,
    http://www.askyogesh.com

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

  • Joining tables with "similar" field values

    I have run into a situation where I want to join two tables on a field called U_LotusBox.    In my main table the the feild can contain values like 1 or 2 or 3 or 1,2,3,4.  That's 1 comma 2 comma 3 comma 4.  My field in the second tables contains only single digit values, like 1 ,2, 3 up to 5.
    When the two fields are identical I am able to retrieve data.  But if my field in the main contains a value of 1,2,3 and my secondary table field value is 2 I get no data returned because the two fields are not identical.  
    Is it possible to have a join that is "fuzzy" meaning that if the main table field values contains the value of the secondary field value, 2 in my example would it be possible to return data?
    Any thoughts would be appreciated.

    Ralph,
    Here in high-level details is an SQL example of creating two tables (test1 and test2) with one column in each table (col_a and col_b, respectively) to show how a join on a substring of one column can be tied to a column of another table:
    create table test1 (col_a char(5))
    create table test2 (col_b char(1))
    insert into test1 values ('1')
    insert into test1 values ('1,2,3')
    insert into test2 values ('1')
    insert into test2 values ('2')
    select col_a,test2_tbl1.col_b
    from test1 inner join test2 as test2_tbl1 on col_a=test2_tbl1.col_b or
    substring(col_a,1,1)=test2_tbl1.col_b or
    substring(col_a,3,1)=test2_tbl1.col_b or
    substring(col_a,5,1)=test2_tbl1.col_b
    col_a     col_b
    ~~~~~~~|~~~~~
    1         1
    1,2,3     1
    1,2,3     2
    thanks,
    John

  • Linking 2 tables with Sql Expressions or add command

    Hi
    I want to make a custom table using a union all using cr2008 but I'm unable to find/enable the sql expressios field? It's just not there?
    I've tried using the add command is the database expert but I cant see how to get this work.. I have 2 data sources that each consist of identical tables (but different data).  I have 2 tables I want to link:
    datasource1 statstable
    datasource2 statstable
    So I want to do:
    SELECT * FROM datasource1 statstable
    UNION ALL
    SELECT * FROM datasource2 statstable
    but it wont let me do this as the 2 stats tables are in different datasouces.
    I would really appreciate any help you can give me.
    thanks

    you can not do this unless you use busines views.
    you can not create one report based on two different datasources using crystal reports,
    my advice to you to solve this problem
    start to look for the "business views"
    which allow you to create a strucutre based on many different datasources, you create 2 connections for your datasources and map them in the view.
    then you use those business views in crysal reports to create you report.
    it may looks complicated, but i admit its too easy and not hard.
    you can get a small book about business views manager which comes with BO XI R2 or Xi 3.0
    from the business objects support site.
    i hope it was clear for you
    good luck

  • Join Table with Collection Array Type

    Hi All,
    I'm trying to join 2 types of tables (real table and array collection type)
    When I wrote this code:
    Declare
    -- Types
    Type cArr Is Record (col1 Number);
    Type tArr Is Table Of cArr Index By Binary_Integer;
    -- Objects
    ocArr cArr;
    otArr tArr;
    Begin
    -- Set Array Table
    ocArr.col1 := 1;
    otArr(1) := ocArr;
    ocArr.col1 := 3;
    otArr(2) := ocArr;
    -- Fetch Records
    For Rec in (Select col1 From Table(otArr) Arr)
    Loop
    Dbms_Output.Put_Line(Rec.col1);
    End Loop;
    End;
    I Get This Error:
    ORA-06550: line 10, column 64:
    PLS-00382: expression is of wrong type
    ORA-06550: line 10, column 58:
    PL/SQL: ORA-22905: cannot access rows from a non-nested table item
    ORA-06550: line 10, column 21:
    PL/SQL: SQL Statement ignored
    I know that I can Use this as sn answer:
    For Rec In 1..2
    Loop
    Dbms_Output.Put_Line(otArr(Rec).Col1);
    End Loop;
    But I need later on to use this collection join with another real table based on values compare like:
    For Rec in (Select a.Col2 From a,(Select col1 From Table(otArr)) Arr Where a.Col1 = Arr.Col1)
    Loop
    Dbms_Output.Put_Line(Rec.col1);
    End Loop;
    Can someone tell me where I'm wrong and how to fix it?
    Thanks,

    Welcome to the forum.
    Don't use a PL/SQL type, but an SQL type.
    http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:2270447621346#tom3041776036531
    Do a search on ORA-22905 on this forum for more examples.

  • Polling for new Data in Tables with SQL-functions

    Hi
    In my table I have 2 columns:
    event_state : integer (0 = unread, 1 = read)
    min_process_time : date
    In the DB-Adapter-Wizard I can configure my event_state-Field for using as logical delete field. In the SQL-Query there is a
    ... WHERE event_state=0
    But, I only want to query all new entries in this table, where
    min_process_time > SYSDATE.
    How can I configure my toplink-mapping, that SYSDATE can be used in the polling-query? If I use plain-sql instead of the expression from the Wizard (last page), then this sql-statement is ignored. In an expression I only can use a constant-value.
    Any idea?
    Thanks
    Gregor

    Hi
    I am creating a database Polling (logical delete OPEN to CLOSED) adapter that polls a table for records which have a "SCHEDULED" date field.
    The Polling Adapter should pick up those records where the status is OPEN and SCHEDULED<=SYSDATE.
    DB Adapter wizard does not allows this where clause(SCHEDULED<=SYSDATE) to be set; so i tried modifying the Toplink SQL with custom SQL. But it does not works. Please suggest a workaround.
    Please help.
    Thanks
    Debashis

  • 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

Maybe you are looking for

  • Custom field not appearing in Japanese language in some pages of SRM portal

    Hi, We have a requirement to add a customer field(a check box) to the shopping cart. To do this we have enhanced a Webdynpro component along with the desired changes in the shopping cart header table. The problem that we are facing is that, this cust

  • IDES server Password reset link --- Not Opening

    Dear Concern ,                                  IDES server daily password reset link is not opening from yesterday. Kindly let know when this might be corrected. Best Regards Keerthan Kumar

  • Lightroom & Layers...what are the chances ?

    My current workflow is Lightroom mainly > Photoshop CC for Layers, Actions etc. I also use Nik [Google] plugins. This set-up is absolutely spot-on and covers just about any image scenario likely to crop up [for me]. The problem is that PS CC is compl

  • SBWP in SRM

    Hi, I want a work item in my SRM inbox, but it should appear to the user in his SRM inbox on web, and when he executes it, it should show him any page like the shopping cart/PO create change etc. Only that page will be developed by me with one custom

  • Duplicating Conditions in Schema

    Hi All I want to link a Delivery Cost Condition to the Discount Condition. e.g. Condition ZAB1 - Discount Condition - Percentage - Negative Condition ZAB2 - Delivery Cost - Percnentage - Positive I want to flow the Percentage of the Delivery Cost Con