找出前2行之间的差异

时间:2017-05-18 10:25:32

标签: sql sql-server

我正在努力研究表格中所有列的前2行之间的差异。我将只指定一列以使这更容易。我是SQL新手,所以如果这很容易就道歉。我在SSMS上,到目前为止我认为我需要内连接表然后比较table1的第1行和table2的第2行。 id列的工作原理是最新的行是最高的id。我需要获得最高的id然后是第二高的id(第2行)并找到差异。

SELECT Table1.id,
   Table1.transferdate,
   Table1.payment,
   Table2.id,
   Table2.transferdate,
   Table2.payment
FROM Table1 AS Table1
INNER JOIN Table2 AS Table2 ON Table1.id = Table2.id

我希望看到付款列中昨天(最上一行)和前一天与该(第二行)之间的差异。付款列应该随着数据添加到前几天而增加。在INNER JOIN之后我还不知道该去哪里,我尝试过的任何工作都没有。

我目前拥有的数据示例:

id | transferdate |payment | debt   | mailing_batch
46 | 2017-05-18   |651681  | 616816 | 1861651
45 | 2017-05-17   |601680  | 516168 | 1616866

我想要的是差异:

id | transferdate |payment | debt   | mailing_batch
1  |       1      |50001   | 100648 | 244785

我只希望看到每列前2名之间的差异。我会删除选择列名称,只留下我使用过TOP功能的TOP1吗?

对任何其他行不感兴趣。始终排在前2位,因为这是一个数据副本表,它是确保数据在业务设置中正确更新的一种方法。

3 个答案:

答案 0 :(得分:1)

SELECT Top 1 Table1.id,
Table1.payment-LEAD(Table1.payment,1) over(order by Table1.id desc)
FROM Table1 AS Table1
INNER JOIN Table2 AS Table2 ON Table1.id = Table2.id
order by Table1.id desc

如果您使用的是sql server 2012或更高版本,则可以使用上述查询。

答案 1 :(得分:0)

;With CTE(id , transferdate ,payment , debt   , mailing_batch)
AS
(
SELECT 46 , '2017-05-18'   ,651681  , 616816 , 1861651 UNION ALL
SELECT 45 , '2017-05-17'   ,601680  , 516168 , 1616866
)

SELECT Id
    ,transferdate
    ,payment
    ,debt
    ,mailing_batch
FROM (
    SELECT (LEadId - Id) AS Id
        ,DATEDIFF(DAY, transferdate, Leadtransferdate) AS transferdate
        ,(Leadpayment - payment) AS payment
        ,(Leaddebt - debt) AS debt
        ,(Leadmailing_batch - mailing_batch) AS mailing_batch
        ,ROW_NUMBER() OVER (
            ORDER BY (
                    SELECT 1
                    )
            ) AS Seq
    FROM (
        SELECT *
            ,LEAD(id) OVER (
                ORDER BY id
                ) AS LEadId
            ,LEAD(transferdate) OVER (
                ORDER BY transferdate
                ) AS Leadtransferdate
            ,LEAD(payment) OVER (
                ORDER BY payment
                ) AS Leadpayment
            ,LEAD(debt) OVER (
                ORDER BY debt
                ) AS Leaddebt
            ,LEAD(mailing_batch) OVER (
                ORDER BY mailing_batch
                ) AS Leadmailing_batch
        FROM CTE
        ) Dt
    ) Final
WHERE Final.Seq = 1

输出

id | transferdate |payment | debt   | mailing_batch
1  |       1      |50001   | 100648 | 244785

答案 2 :(得分:-2)

您使用的是哪个版本的sql server?如果它是2012+,那么LEAD和LAG功能将起作用。您可以详细了解他们herehere 自己动手,因为它们真的很容易。展示一些努力,如果不行,我会帮助你。

评论后更新

public class Test {
    public static void main(String[] args) {
        for (int i = 0; i < 4; i++)
            new Thread(Test::maxCpu).start();
    }
    private static void maxCpu() {
        for (long end = System.currentTimeMillis() + 10000; end > System.currentTimeMillis(); );
    }
}

截图:

输入表 input

输出表 output

PS:您不需要2个单独的表格。您的问题可以通过1个表本身来解决。