SQL - 计算两天

时间:2017-10-30 17:04:06

标签: sql sql-server

我有一张像

这样的表格
CREATE TABLE [dbo].[Log](
    [Id] [BIGINT] IDENTITY(1,1) NOT NULL,
    [GuidId] [UNIQUEIDENTIFIER] NOT NULL,
    [TableName] [VARCHAR](50) NULL,
    [CreatedDate] [DATETIME] NULL,
    [Operation] [VARCHAR](50) NULL,
    [Status] [VARCHAR](50) NULL,
    [UserId] [VARCHAR](50) NOT NULL)

我试图获得像

这样的查询
SELECT TOP 25 UserId, TableName, Operation, COUNT(1) Records 
FROM dbo.Log  
WHERE CreatedDate > GETDATE() - 1 
    AND Status='failed' 
GROUP BY UserId, TableName,Operation

我需要添加另一列,以便在同一个select中输出具有GetDate()的7个条件的count。 分享一些想法

2 个答案:

答案 0 :(得分:0)

这样的东西?

SELECT TOP 25
    UserId
    , TableName
    , Operation
    , SUM(CASE WHEN CreatedDate > GETDATE() - 1 THEN 1 ELSE 0 END) Records1Day
    , COUNT(1) Records7Days
FROM dbo.Log
WHERE
    CreatedDate > GETDATE() - 7
    AND Status='failed'
GROUP BY
    UserId
    , TableName
    , Operation

答案 1 :(得分:0)

如果我理解正确,您希望最新的UserID失败,其具有MAX(Cre​​atedDate)>昨天。下面的子查询dT使用MAX(Cre​​atedDate)作为用户ID,并使用HAVING进行过滤。这是以降序的faildate顺序排序。我进行了subqueried,因为你在此之前添加了你想知道7天日期的条件,并且接收查询执行此操作...使用DATEADD从[最近用户ID失败]日期减去7天。

SELECT dT.UserId
      ,dT.[Most Recent UserID Failure]
      ,DATEADD(DAY, -7, dT.[Most Recent UserID Failure]) AS [7 Days ago]
      ,(SELECT COUNT (*) 
          FROM #Log 
         WHERE UserId = dT.UserID
           AND CreatedDate >= DATEADD(DAY, -7, CAST(dT.[Most Recent UserID Failure] as date))
           AND CreatedDate <= dT.[Most Recent UserID Failure]
           AND Status = 'failed'
       ) AS [Num Fails]
  FROM (        
        SELECT TOP 25
               UserID
              ,MAX(CreatedDate) AS [Most Recent UserID Failure]
          FROM Log
         WHERE Status = 'failed'   
        GROUP BY UserID
        HAVING MAX(CreatedDate) > GETDATE() - 1
        ORDER BY [Most Recent UserID Failure] DESC
      ) AS dT