简体   繁体   中英

Self Join table and sum same column with difference criterea (SQL Server)

Seeking help with showing me how I may join the below queries together but also sum together the results for issues and transfers in a new column.

I have tried to do them as sub queries as well as inner and outer joins with NO success.

Any Ideas or direction to search on would be greatly appreciated.

Current queries and results:

--30 & 90 day issues query
SELECT 
    Table1.itemnum, SUM(Table1.quantity) AS SumOfquantityIssue
FROM 
    Table1
WHERE 
    Table1.transdate > GETDATE() - 30 
    AND Table1.issuetype = 'ISSUE' 
    AND Table1.gldebitacct IS NOT NULL
    AND Table1.fromstoreloc IN ('WFOWH', 'WFOPY')
GROUP BY 
    Table1.itemnum
ORDER BY 
    Table.itemnum;

Results I get from this query:

itemnum   SumOfquantityIssue
----------------------------
  1007       -1.00

Second query:

--30 & 90 day transfers query
SELECT 
    Table1.itemnum, SUM(Table1.quantity) AS SumOfquantityTransfer
FROM 
    Table1
WHERE 
    Table1.transdate > GETDATE() - 30 
    AND Table1.issuetype = 'TRANSFER' 
    AND Table1.gldebitacct IS NOT NULL
    AND Table1.fromstoreloc IN ('WFOWH', 'WFOPY')
GROUP BY 
    Table1.itemnum
ORDER BY 
    Table1.itemnum;

Results I get from that query:

itemnum SumOfquantityTransfer
------------------------------
   1007     1.00
   2347    20.05

The results I am seeking to get looks like this:

Itemnum      SumOfquantityIssue   SumOfquantityTransfer  Total_Sum
-------------------------------------------------------------------
 1007             1.00                -1.00                 0.00
 2347            20.05                 0.00                20.05

You can do this in one query like so.. join to self.. i haven't run this in SSMS to check .. just going off the top of my head..

    SELECT 
    Table1.itemnum
   , Sum(Table1.quantity) AS SumOfquantityIssue
   , isnull(Sum(Table2.quantity),0) AS SumOfquantityTransfer
   , Sum(Table1.quantity) + isnull(Sum(Table2.quantity),0) as total_sum

    FROM Table1

    LEFT JOIN Table1 as Table2
      ON Table2.itemnum = Table1.itemnum
      AND Table2.issuetype ='TRANSFER' 
      AND Table2.gldebitacct Is Not Null
      AND Table2.fromstoreloc in('WFOWH','WFOPY')
      AND Table2.transdate>getdate()-30 

    WHERE Table1.transdate>getdate()-30 
    AND Table1.issuetype ='ISSUE' 
    AND Table1.gldebitacct Is Not Null
    AND Table1.fromstoreloc in('WFOWH','WFOPY')
    GROUP BY Table1.itemnum
        ORDER BY Table.itemnum;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM