【问题标题】:Query with Min and Max results from Subquery使用子查询的最小和最大结果进行查询
【发布时间】:2017-07-22 05:56:53
【问题描述】:

我需要有关 sql 查询的帮助。我用的是Sql Server Management Studio,相关字段是:

Employees.Id

Employees.Name

Events.Employee_Id

Events.DateTime

为每个员工/日期(不是 DateTime)组合返回一条记录的最有效方法是什么,其中包含每个员工/日期组合的 Name、min(DateTime)、max(DateTime) 以及以小时为单位的增量?

【问题讨论】:

    标签: sql max min


    【解决方案1】:

    简单的方法是使用JoinMin/Max 聚合

    select e.Name,Min(ev.[DateTime]),Max(ev.[DateTime])
    from Employees e
    Left join Events ev  --change it to INNER JOIN if you don't want all the employees
    ON e.Id = ev.Employee_Id
    Group by e.Name
    

    使用Apply 运算符的另一种方法

    select e.Name,oa.MinDate,oa.MaxDate
    from Employees e
    Outer Apply( --change it to Cross Apply if you don't want all the employees
                select Min(ev.[DateTime]),Max(ev.[DateTime]) 
                from Events ev 
                Where e.Id = ev.Employee_Id) oa (MinDate,MaxDate
                )
    

    【讨论】:

      【解决方案2】:

      窗口函数应该是最有效的方法。假设每个名称和日期/时间已经有一行:

      select e.*,
             max(e.datetime) over (partition by name),
             min(e.datetime) over (partition by name),
             (datediff(hours,
                       min(e.datetime) over (partition by name),
                       max(e.datetime) over (partition by name)
             ) as diff_in_hours
      from events e;
      

      【讨论】:

        【解决方案3】:

        非常感谢您的回复。这个问题一定不是很清楚,因为你们两个解决方案都很相似,但不是我想要的。他们确实让我回去从头开始重试,我不确定为什么我没有首先尝试这个,但下面是返回我正在寻找的结果。在我的问题中,我更改了表/字段名称并省略了我知道自己可以实现的要求,以使问题尽可能简单易读,这就是为什么看起来如此不同:

        SET DATEFIRST 1
        SELECT e.IdEmpNum,
               m.tFirstName,
               m.tLastName,
               convert(varchar(10), e.dtEventReal, 101) as "event_date",
               convert(varchar(20), min(e.dtEventReal), 108) as "min",
               convert(varchar(20), max(e.dtEventReal), 108) as "max",
               round((datediff(minute,
                         min(e.dtEventReal),
                         max(e.dtEventReal)
               )/60.0), 2) as "hours"
        FROM tblEvents e INNER JOIN tblEmployees m ON e.IdEmpNum = m.iEmployeeNum
        WHERE e.dtEventReal >= dateadd(day, 1-datepart(dw, getdate()), convert(date,getdate()))
        GROUP BY e.IdEmpNum, m.tFirstName, m.tLastName, convert(varchar(10), e.dtEventReal, 101)
        ORDER BY e.IdEmpNum, convert(varchar(10), e.dtEventReal, 101) ASC;
        

        DATEFIRST 和 WHERE 条件指定仅返回本周的事件。我现在唯一遇到的问题是对“小时”计算求和。我收到错误消息“SQL Server 无法对包含聚合或子查询的表达式执行聚合函数”。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-17
          • 2010-12-26
          相关资源
          最近更新 更多