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

Similar Messages

  • How to create a table with multiple select on???

    Hi all,
            I am  new to webdynpro and my requirement is to create a  table with multiple selection on.I have to add abt 10 rows in the table but only 5 rows should be visible and moreover a verticalscroll should be available to view other rows.Can anybody explain me in detail how to do that.Please reply as if you are explaining  to a newcomer.Reply ASAP as i have to do it today.
                                                                           Thanxs

    Hi,
    1. Create a value node in your context name Table and set its cardinality to 0:n
    2. Create 2 value attributes within the Table node name value1 and value2
    3. Goto Outline view> Right click on TransparentUIContainer>Apply Template> Select Table>mark the node Table and it's attributes.
    you have created a table and binded its value to context
    Table UI properties
    4.Set Selection Mode to Multi
    5.Set Visible Row Count to 5
    6.ScrollableColCount to 5
    In your implemetaion, you can add values to table as follow:
    IPrivate<viewname>.ITableElement ele = wdContext.nodeTable().createTableElement();
    ele.setValue1(<value>);
    ele.setValue2(<value>);
    wdContext.nodeTable().addElement(ele);
    The above code will allow you to add elements to your table node.
    Regards,
    Murtuza

  • How can i build table with two user name columne  ?

    How can I build view with two columns for user name ( one create and the other
    Can change also ) 
    And to display full name ( the user name is the key but not display  ) ?

    Hi,
    Creating View
    •     From initial screen of data dictionary(T.Code: SE11), enter the name of object i.e. view.
    •     Select view radio button and click on the push button.
    •     Dialog box is displayed for types of views.
    •     Select the view type.
    •     On the next screen, you have to pass following parameters.
    •     Short text
    •     In the table box you need to enter the table names, which are to be related.
    •     In join table box you need to join the two tables.
    •     Click on the TABFIELD. System displays the dialog box for all the table fields and user can select the fields from this screen. These fields are displayed in the view fields box.
    •     Save and Activate: When the view is activated, view is automatically created in the underlying database system. As long as the table exists in the database, the view also exists (Unless you delete it).
    Regards,
    Bhaskar

  • 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 can I use TrueSequenceFactory with multiple sequences

    In the post "How to use existing Oracle sequences using KODO" answered
    by Marc Prud'hommeaux a "sample code" was given. But seems to me that
    example will only work with a single Oracle sequence for the entire
    system. Is this right?
    How can I use TrueSequenceFactory with primary-keys and their
    respective existing sequences? Can you (SolarMetric guys) provide me a
    sample code?

    The problem is that you are using application-identity. When you
    specify an objectid-class, we treat is automatically as application
    identity. To resolve this, I would recommend removing both the
    objectid-class and identity-type atributes from your class. With
    "objectid-class" in place, we asssume that you wil take care of identity.
    Eduardo Bobsin Machado wrote:
    I'm using Kodo 2.4.0, Oracle 9i, JBoss 3.0.4, the Kodo jars are in the
    JBoss' lib/ext.
    Well, I'll show what I have...
    This is the script of my table:
    CREATE TABLE LINEUP_VOYAGE (
    VOYAGEID NUMBER (10) NOT NULL,
    VESSEL_NAME VARCHAR2 (1000) NOT NULL,
    CONSTRAINT PK_LINEUP_VOYAGE
    PRIMARY KEY ( VOYAGEID ) ) ;
    This is an excerpt of my .jdo file:
    <class name="LineupVoyage" objectid-class="LineupVoyageId"
    identity-type="datastore">
    <extension vendor-name="kodo" key="table" value="LINEUP_VOYAGE"/>
    <extension vendor-name="kodo" key="sequence"
    value="LINEUP_VOYAGEID_SEQ"/>
    <extension vendor-name="kodo" key="pk-column" value="VOYAGEID"/>
    <extension vendor-name="kodo" key="lock-column" value="none"/>
    <extension vendor-name="kodo" key="class-column" value="none"/>
    <field name="vesselName">
    <extension vendor-name="kodo" key="data-column"
    value="VESSEL_NAME"/>
    </field>
    <!--field name="id" primary-key="true">
    <extension vendor-name="kodo" key="data-column"
    value="VOYAGEID"/>
    </field-->
    </class>
    As you can see, the "id" field is commented.
    And this is my class:
    package br.com.fertimport.entity;
    import java.util.*;
    public class LineupVoyage {
         private String vesselName;
    //     private long id;
    //     public LineupVoyage(long id) { this.id = id; }
    //     public long getId() { return id; }
    //     public void setId(long id) { this.id = id; }
         public String getVesselName() { return vesselName; }
         public void setVesselName (String vesselName) { this.vesselName =
    vesselName; }
    The "id" attribute is commented.
    Now the questions...
    To use ClassSequenceFactory must the identity-type of my entities be
    application or datastore?
    Is the "objectid-class" parameter required in this case?
    As you see, all references to the "id" property are commented. Can I
    use this property to represent my object id?
    If not, how can I identify my object with something like a long?
    The last question is related to my architecture: one VM with the EJBs
    (entity and session) and another VM with the web classes and JSPs,
    connected by a session facade. I don't want to use any Kodo or JDO stuff
    in the web tier. Is this possible?
    Stephen Kim
    [email protected]
    SolarMetric, Inc.
    http://www.solarmetric.com

  • How can i join PO with GRPO

    Hi,
    I make query as belown to join PO with GRPO.I wnat to calculate Quantity from PO to GRPO but in my query it show duplicate record i also use distinct but useless.My query as below.
    SELECT T1.DocNum [PO No], T1.DocDate [PO Date], T3.ItemCode, T3.Dscription, T3.U_CostCentre, T3.DocEntry [GRN No], T0.DocDate [GRN Date],T3.Quantity'GRIR Quantity',T2.Quantity 'PO Quantity',
    T3.Quantity-T2.Quantity 'Balance Quantity'
    FROM OPDN T0 , OPOR T1, POR1 T2, PDN1 T3
    WHERE T1.DocEntry = T2.DocEntry
    and T0.Docnum = T3.Docentry
    and T3.BaseRef  =  T1.DocNum
    and T2.ItemCode = T3.ItemCode
    and T3.DocDate between [%0] and [%1]
    Can any body help in this regards.
    Sohail Anwar Ali

    Hi Sohail,
    As i understand, you want to know till now how much of quantity stills needs  to be delivered, in that case instead of trying joining two tables i would suggest to try this query which gives you
    Purchase Order Document No,
    Purchase Order Date,
    Vendor Name,
    Item Code,
    Item Description,
    Ordered Quantity,
    Received Quantity,
    Open Quantity.
    as the filed OpenQty stores the Quantity yet to receive for that particular Purchase Order. As this approach is much more flexible
    Query
    SELECT T0.DocNum, T0.DocDate, T0.CardName, T1.ItemCode, T1.Dscription, T1.Quantity,
    (T1.Quantity-T1.OpenQty) as "Recevied Quantity",
    T1.OpenQty FROM OPOR T0  INNER JOIN POR1 T1 ON T0.DocEntry = T1.DocEntry WHERE T0.DocDate >=[%0] and
    T0.DocDate <=[%1]
    I hope this helps out your issue
    regards,
    Shreyas

  • How can use full app with multiple monitor

    in Lion and Mountain Lion
    when i use Multiple Monitors and move any app in full-screen mode
    its become in one monitor and other monitor become blank
    but it seems usefull that other monitor show another app in fullscreen mode
    how can i do this ?
    and sorry for my bad english!!

    Sorry to say, but it is designed to work that way.
    The only way around it that I know of is, not to use full-screen but just fill the screen with the application that you are using.
    A

  • How can I join PRPS with DRAD?

    Hi,
    I would like to join the table PRPS and DRAD in order to see all documents linked to a certain PSP. I tried to join DRADOBJKY with PRPSPSPNR but it doesn't work since the OBJKY is different from the psp-number. If I'm doing this with MARA~MATNR it works. Strange. can someboy help me?
    Thanks

    Hello,
    Can you check if PRPS-OBJNR = DRAD-OBJKY ?
    If this is not successful, then use the conv. exit  CONVERSION_EXIT_ABPSP_INPUT, pass the PRPS-OBJNR get the internal number.
    Now check that this internal number matches with DRAD-OBJKY.
    Plz revert back.
    BR,
    Suhas

  • How can I share Catalog with multiple users?

    I have Mac OSX 10.7.5
    The catalog exists on a shared LOCAL folder that other users have read-write access to
    The catalog works fine for the 1st user (no issues viewing, tagging, or updating photos & repairing it yields no issues)
    However when I try to open this catalog with any other user I receive an error that the catalog may be corrupt and therefore cannot be opened...
    Has anyone been able to share their catalog with multiple users on a Mac?
    thanks
    -Jay

    If anyone runs into the same issue - I figured out why it wasn't working for me. Turns out it was actually an issue with folder permissions.
    Despite the catalog being in a shared folder that all users can read/write to - Macs apparently don't understand inheritance & I needed to set the same read/write access to every sub-folder (the catalog folder & all of it's sub folders) as well.
    This fixed my issue.
    The Catalog is now shared between multiple users on the local drive with all the photos/videos stored on a NAS drive.

  • 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 use airplay with multiple speakers from my iPod?

    I recently purchased a bluetooth wireless speaker in hopes that, while the ipod is docked on a speaker system, I can listen to my music from both set of speakers.  Is there anyway to use multiple speakers with my ipod through the airplay system or an app that I can download to enhance my music listening experience?

    Based on previous discussions, You can only AiPlay to one set of speakers.

  • How can I open safari with multiple home pages

    Hi All
    On my iPhone 4 I always follow the same four websites (2x e-mail, 1x news and 1x sport page).  Is there a way that I can set Safari on the iPhone to open these four pages on startup.  i.e. open up with 4 home pages.
    Thanks in advance
    Sathers

    It strikes me that it should be possible to do that (or something similar) by building a safari extension, TC. Both Sessions and SafariRestore are able to launch multiple tabs from a previous session, so it seems like you should be able to create an extension that launches multiple tabs open to specific sites when Safari is launched.

  • How can I format-table with two different variables

    I have a script who's purpose is to go through all the mailboxes in exchange and look for any with SG_ or Group listed in the Full Access Permissions.  The script works though I'm having trouble formatting the data in a way that I can use it in Excel.
    Ultimately I'd like it to report the Name of the mailbox and the name of the entry listed in the Full Access Permissions that has SG_ or Group in the name. Currently the output is the name of the mailbox and then on a separate line the full name of the security
    group.
    I'm trying to have it so that each part is in it's own column. That will make it easy to review in excel.
    $Grabmailbox = Get-Mailbox -Resultsize Unlimited
    foreach ($mailbox in $Grabmailbox){
    $Getpermission = Get-MailboxPermission $mailbox | where { ($_.User -like "corp\SG_*") -or ($_.User -like "corp\*_group") }
    if ($Getpermission -ne $null) {
    echo "$mailbox +  "$Getpermission | FT User |Out-File c:\Script\VerifiedSG.txt -Append
    else{
    echo "$mailbox + No SG detected" | Out-File c:\Script\VerifiedSG.txt -Append

    Hi Yan,
    Thanks for the response but what I am looking for is even simpler than that.  
    The script goes through every mailbox we have. 
    It checks the Full Access Permissions for anything with SG_ or group listed in the Full access permissions.
    It then should write out to a file the name of the mailbox and the entry in the Full access permissions that contains SG_ or _Group
    so something like this:
    Mailbox Name <---New ColumN--->Entry
    Mailbox1<---New ColumN--->SG_Mailbox1
    Ignore the <---New ColumN---> as I simply put that in to emphasize space between the two columns.

  • How can I merge layers with multiple layer styles added to them?

    So I have this issue where I have to merge lots of layers in order to finish the job. Thing is that two of them have layer styles added to them. Each one has two different layers styles added to it. If I try to merge the layers, the effect won't stay the same and only one layer style will apply (and not even this one works correctly). Is there any cure for this? Thank you!

    Here is how it looks before I merge the layers.
    And here is how it looks after I merge the layers.
    Why won't it stay the same?

  • TO DRAW A TABLE WITH MULTIPLE ROWS AND MULTIPLE COLOUMNS IN FORM

    Hi,
       How to draw a table with multiple rows and columns seperated by lines in form printing?

    check this
    http://sap-img.com/ts003.htm
    Regards
    Prabhu

Maybe you are looking for

  • Issue with Write Back

    Hi All, I have a requirement where the user can writeback to a field. The table has two columns COMBI and SERVICE_REV. COMBI is the key cloumn . Below is the code in the writeback template. <?xml version="1.0" encoding="utf-8"?> <WebMessageTables xml

  • How do I stop Ical from stealing focus?

    Is anyone aware of a way to stop ical from stealing focus when events are created or modified?  I do not want to lose the ability to fast switch to the app when it is in another space. I have some individuals on my team at work who tend to edit multi

  • My sing keeps freezing and skipping to totally seperate song! why?

    i bought a song recently and it stops in the middle and it either goes to the next song or two songs ahead. It works on my siblings ipod's and we use the same computer is there a reason for this and how do i fix it?

  • Computer crushed with iTunes...

    Hi, My computer crushed with my itunes in it. Now I have a new computer. How can I transfer it to my new computer. I am using Windows XP. thanks.

  • JTable and Adjusrt Row Height

    Hi, 1. Can we adjust variable row height for each row, 2. Also as we adjust the column widht, can we adjust the row height by dragging, 3.Suppose i have JTextArea as a cell renderer , how can i display all the text in a row with out having to use a s