按第二行中的记录值分组

时间:2014-12-14 09:02:58

标签: sql sql-server tsql

我有以下查询

Select 
   Date, Item_Code, 
   SUM(In_Quantity) as In_Quantity, 
   SUM(Issue_Quantity) as Issue_Quantity, 
   (SUM(In_Quantity) - SUM(issue_Quantity)) as BalanceQty    
from
   (select 
        tbl_add_product.Date as Date, tbl_add_product.Item_Code, 
        tbl_add_product.In_Quantity, 0 as Issue_Quantity 
    from 
        tbl_add_product
    where 
        Item_Code = 'pen' 

    union ALL

    select 
        tbl_issue_product.Date as Date, tbl_issue_product.Item_Code, 
        0 as In_Quantity, Issue_Quantity 
    from 
        tbl_issue_product
    where 
        Item_Code = 'pen') X 
group by 
    Item_Code, Date  

返回以下结果:

Date         Item_Code  In_Quantity Issue_Quanitity BalanceQty
--------------------------------------------------------------
2014-12-02    pen           100         0             100
2014-12-03    pen           50         50               0

我想在第二排100分。逻辑是第一行的余额Qty应该添加到In_Qty,这样当从Issue_Quantity中减去BalanceQty时,它会给{{1}}

3 个答案:

答案 0 :(得分:1)

将其包装在另一个子查询中,然后使用:

SELECT *, SUM(BalanceQty) OVER (PARTITION BY Item_Code ORDER BY [Date])
FROM ( ... ) o

答案 1 :(得分:0)

--variant using LAG() OVER () function

SELECT  [Date] ,
                Item_Code ,
                SUM(In_Quantity) AS In_Quantity ,
                SUM(Issue_Quantity) AS Issue_Quantity ,
                ( SUM(In_Quantity) - SUM(issue_Quantity) )
                + COALESCE(LAG(SUM(In_Quantity) - SUM(issue_Quantity)) OVER ( PARTITION BY item_code ORDER BY [date] ),
                           0) AS BalanceQty
        FROM    ( SELECT    tbl_add_product.Date AS Date ,
                            tbl_add_product.Item_Code ,
                            tbl_add_product.In_Quantity ,
                            0 AS Issue_Quantity
                  FROM      tbl_add_product
                  WHERE     Item_Code = 'pen'
                  UNION  ALL
                  SELECT    tbl_issue_product.Date AS Date ,
                            tbl_issue_product.Item_Code ,
                            0 AS In_Quantity ,
                            Issue_Quantity
                  FROM      tbl_issue_product
                  WHERE     Item_Code = 'pen'
                ) X
        GROUP BY Item_Code ,
                Date

答案 2 :(得分:0)

考虑以下是SUM和所有

之后的第一个查询的结果

enter image description here

以下是示例代码

SELECT * INTO #TEMP
FROM
(
    SELECT '2014-12-02' [Date],    'pen' Item_Code,100  In_Quantity,0 Issue_Quanitity,100 BalanceQty
    UNION ALL
    SELECT '2014-12-03',    'pen',           50,         50,               0
)TAB

使用自联接获取上一条记录

;WITH CTE1 AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY  Item_Code,[DATE])RNO,* 
    FROM #TEMP T1
)
SELECT C1.[Date] ,C1.Item_Code,C1.In_Quantity,
C1.Issue_Quanitity,
ISNULL((C2.Issue_Quanitity+C1.In_QuantitY)+C1.Issue_Quanitity ,C1.In_Quantity)BalanceQty2
FROM CTE1 C1 
LEFT JOIN CTE1 C2 ON C1.RNO=C2.RNO+1

<强> RESULT

enter image description here