从当前月份和上个月检索最后一条记录

时间:2017-03-19 22:44:55

标签: sql sql-server sql-server-2012


我需要从当前月份和上个月获得最后记录的值。每月大约有4,600条记录。

以下是我尝试过的代码,但它会返回' 0'这两个月而不是价值:

SELECT a.LogPoint as [Meter]
,max(CASE WHEN c.DateTimeStamp = dateadd(MM,-1,getdate()) THEN c.FloatVALUE ELSE 0 END) as [Total LAST Month]
,max(CASE WHEN c.DateTimeStamp = getdate() THEN c.FloatVALUE ELSE 0 END) as [Total This Month]
FROM 
   SWR.dbo.LoggedEntities a
  ,SWR.dbo.TrendLogRelation b
  ,SWR.dbo.LogTimeValues c
WHERE
      a.GUID = b .GUID
  AND a.Type LIKE 'trend.ETLog'
  AND a.LogPoint = 'WsumOut_Trnd'
  AND b.EntityID = c.ParentID
GROUP BY a.LogPoint

非常感谢任何帮助 欢呼声。

3 个答案:

答案 0 :(得分:1)

我认为LogPoint是主键。正确?在这种情况下,请检查以下内容:

    SELECT mainA.LogPoint AS [Meter],
       lastMonth.FloatValue AS [Total LAST Month],
       thisMonth.FloatValue AS [Total This Month]
FROM SWR.dbo.LoggedEntities mainA
     CROSS APPLY
     (
       SELECT TOP 1 c.FloatVALUE
       FROM SWR.dbo.LoggedEntities a
           JOIN SWR.dbo.TrendLogRelation b ON a.GUID = b.GUID
           JOIN SWR.dbo.LogTimeValues c ON b.EntityID = c.ParentID
       WHERE a.LogPoint = mainA.LogPoint 
       ORDER BY c.DateTimeStamp DESC
     ) thisMonth
    CROSS APPLY
     (
       SELECT TOP 1 c.FloatVALUE
       FROM SWR.dbo.LoggedEntities a
           JOIN SWR.dbo.TrendLogRelation b ON a.GUID = b.GUID
           JOIN SWR.dbo.LogTimeValues c ON b.EntityID = c.ParentID
       WHERE a.LogPoint = mainA.LogPoint AND c.DateTimeStamp <= DATEADD(MM,-1,GETDATE()) 
       ORDER BY c.DateTimeStamp DESC
     ) lastMonth
WHERE a.Type LIKE 'trend.ETLog'
      AND a.LogPoint = 'WsumOut_Trnd';

刚才意识到我错过了上个月的日期检查。现在补充道。尝试:)

答案 1 :(得分:0)

getdate()包括时间和日期,这就是为什么你没有得到任何匹配。

一种选择是将两个值都转换为日期,然后进行比较。

答案 2 :(得分:0)

我开始之前的两个要点:

  1. 从不FROM子句中使用逗号。 始终使用明确的JOIN语法。
  2. 表别名应为表格的缩写。
  3. 然后,您想使用row_number()

    SELECT LogPoint as [Meter],
           max(CASE WHEN seqnum = 1 AND
                         DATEDIFF(month, DateTimeStamp, getdate()) = 1
                    THEN cltv.FloatVALUE
               END) as [Total LAST Month],
           max(CASE WHEN seqnum = 1 AND
                         DATEDIFF(month, DateTimeStamp, getdate()) = 0
                    THEN ltv.FloatVALUE 
               END) as [Total This Month]
    FROM (SELECT le.LogPoint, ltv.DateTimeStamp,
                 ROW_NUMBER() OVER (PARTITION BY YEAR(DateTimeStamp), MONTH(DateTimeStamp)
                                    ORDER BY DateTimeStamp DESC
                                   ) as seqnum
          FROM SWR.dbo.LoggedEntities le JOIN
               SWR.dbo.TrendLogRelation tlr
               ON le.GUID = tlr.GUID JOIN
               SWR.dbo.LogTimeValues ltv
               ON ltr.EntityID = ltv.ParentID
          WHERE le.Type LIKE 'trend.ETLog' AND
                le.LogPoint = 'WsumOut_Trnd' AND
                DATEDIFF(month, ltv.DateTimeStamp, getdate()) IN (0, 1)
         ) x
    WHERE seqnum = 1;