SQL Server报告通过比较连续的行

时间:2015-02-09 09:18:11

标签: sql-server-2008

我有一张看起来像这样的表:

+--------------+------------+--------+
|     Acno     | ValueDate  | Amount |
+--------------+------------+--------+
| 190010283045 | 20/01/2015 |  -3000 |
| 190010283045 | 20/01/2015 |   3000 |
| 190010283045 | 20/01/2015 |  -3000 |
| 190010283118 | 08/01/2015 |    100 |
| 190010283118 | 08/01/2015 |    100 |
| 190010283266 | 19/01/2015 |  -3500 |
| 190010283266 | 19/01/2015 |   3500 |
| 190010283533 | 14/01/2015 |  -5000 |
| 190010283533 | 16/01/2015 |   5000 |
+--------------+------------+--------+

要求是比较表中的两个连续行:

  1. 如果Acno相同,
  2. 然后如果ValueDate相同
  3. 然后,如果两行中金额的总和是= 0
  4. 然后两行都应标记为1
  5. 标记的行不应再次用于比较。

    因此,上表所需的报告将是:

    +--------------+------------+--------+------+
    |     Acno     | ValueDate  | Amount | Flag |
    +--------------+------------+--------+------+
    | 190010283045 | 20/01/2015 |  -3000 |    1 |
    | 190010283045 | 20/01/2015 |   3000 |    1 |
    | 190010283045 | 20/01/2015 |  -3000 |      |
    | 190010283118 | 08/01/2015 |    100 |      |
    | 190010283118 | 08/01/2015 |    100 |      |
    | 190010283266 | 19/01/2015 |  -3500 |    1 |
    | 190010283266 | 19/01/2015 |   3500 |    1 |
    | 190010283533 | 14/01/2015 |  -5000 |      |
    | 190010283533 | 16/01/2015 |   5000 |      |
    | 190010283533 | 27/01/2015 |  -5000 |      |
    +--------------+------------+--------+------+
    

1 个答案:

答案 0 :(得分:0)

样本表

CREATE TABLE #TEMP(Acno   BIGINT  , ValueDate DATE , Amount NUMERIC(20,2))

INSERT INTO #TEMP
SELECT 190010283045 , '01/20/2015' ,  -3000 
UNION ALL
SELECT 190010283045 , '01/20/2015' ,   3000 
UNION ALL
SELECT 190010283045 , '01/20/2015' ,  -3000 
UNION ALL
SELECT 190010283118 , '01/08/2015' ,    100 
UNION ALL
SELECT 190010283118 , '01/08/2015' ,    100
UNION ALL 
SELECT 190010283266 , '01/19/2015' ,  -3500 
UNION ALL
SELECT 190010283266 , '01/19/2015' ,   3500 
UNION ALL
SELECT 190010283533 , '01/14/2015' ,  -5000 
UNION ALL
SELECT 190010283533 , '01/16/2015' ,   5000 
UNION ALL
SELECT 190010283533 , '01/27/2015' ,   -5000

<强> QUERY

;WITH CTE AS
(
    SELECT ROW_NUMBER() OVER(PARTITION BY ACNO,ValueDate 
    ORDER BY ACNO,(SELECT 0))RNO, *
    FROM #TEMP
)
,CTE2 AS
(
    SELECT C1.*,C2.RNO RNO1,C2.ACNO ACNO1, C2.ValueDate VD,C2.Amount AM,
    CASE WHEN C1.ValueDate=C2.ValueDate AND (C1.Amount+C2.Amount)=0 THEN 1 
    ELSE NULL END COL
    FROM CTE C1
    LEFT JOIN CTE C2 ON 
    (C1.RNO=C2.RNO-1 AND C1.ValueDate=C2.ValueDate) --AND ((C2.RNO-1)%2=0 OR C1.RNO=1))
    WHERE C1.RNO%2 <> 0
)
,CTE3 AS
(
    SELECT RNO,ACNO,ValueDate,Amount,COL FLAG
    FROM CTE2
    UNION ALL
    SELECT RNO1,ACNO1,VD,AM,COL
    FROM CTE2
    WHERE RNO1 IS NOT NULL
)
SELECT ACNO,ValueDate,Amount,FLAG
 FROM CTE3
ORDER BY ACNO,RNO

随意请求任何更改。