MSSQL在联合中彼此相减两行

时间:2018-09-04 05:56:12

标签: sql sql-server

因此,我有一个成功的查询,该查询显示了上个月的第一行以及本月的第一行。此查询显示具有持续用电量计数器的字段。

我需要一个特定字段的差,然后将其乘以.54802并四舍五入到最接近的百分之一。

SELECT *
FROM
(
    SELECT TOP (1) *
    FROM Datebase
    WHERE DATEPART(M, Timestamp) = DATEPART(M, DATEADD(M, -1, GETDATE()))
      AND DATEPART(Yyyy, Timestamp) = DATEPART(Yyyy, DATEADD(M, 0, GETDATE()))
    ORDER BY Timestamp ASC
                          ) AS A
UNION
SELECT *
FROM
(
    SELECT TOP (1) *
    FROM Datebase
    WHERE DATEPART (M, Timestamp) = DATEPART(M, DATEADD(M, 0, GETDATE()))
      AND DATEPART(Yyyy, Timestamp) = DATEPART(YYYY, DATEADD(M, 0, GETDATE()))
    ORDER BY Timestamp ASC
                          ) AS B;

这将输出:

| ID | Timestamp                | 7000AV119   |
---------------------------------------------------
|  1 | 2018-08-01 00:00:03.000  |     3675.59 |
|  2 | 2018-09-01 00:00:03.000  |     3750.93 |

我需要显示它:

| ID | Timestamp                | 7000AV119   | Difference
-----------------------------------------------------------
|  1 | 2018-08-01 00:00:03.000  |     3675.59 |     0
|  2 | 2018-09-01 00:00:03.000  |     3750.93 |    41.29 

2 个答案:

答案 0 :(得分:0)

我会得到两条记录:

select t.*
from (select t.*,
             row_number() over (partition by year(timestamp), month(timestamp) order by timestamp asc) as seqnum
      from Datebase t
      where timestamp >= dateadd(day, 1, eomonth(getdate(), -2))
     ) t
where seqnum = 1;

然后我将使用lag()

select t.*,
       round(([7000AV119] - lag([7000AV119]) over (order by timestamp)
             ) * 0.54802,
             2
            )
from (select t.*,
             row_number() over (partition by year(timestamp), month(timestamp) order by timestamp asc) as seqnum
      from Datebase t
      where timestamp >= dateadd(day, 1, eomonth(getdate(), -2))
     ) t
where seqnum = 1;

第一行返回NULL而不是0。这对我来说更有意义。

答案 1 :(得分:0)

尝试使用滞后功能

with testcte as
(
select *

 from (select top(1) * from DATABASE

  WHERE DATEPART(m, Timestamp) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, Timestamp) = DATEPART(yyyy, DATEADD(m, 0, getdate()))
 order by Timestamp ASC)  a

union

select * 

from (select top(1) * from DATABASE 
WHERE DATEPART(m, Timestamp) = DATEPART(m, DATEADD(m, 0, getdate()))
AND DATEPART(yyyy, Timestamp) = DATEPART(yyyy, DATEADD(m, 0, getdate()))
 order by Timestamp ASC) b
)

select id,Timestamp,7000AV119,7000AV119- LAG(7000AV119,1,0) OVER (ORDER BY id) AS Diff
from testcte