使用GROUP BY时选择其他字段

时间:2014-03-11 21:43:04

标签: sql sql-server jpa ebean

我正在使用MSSQL 2008 R2,并遇到以下情况的问题:

通过以下查询,我将获得我期望的数据(每个日期的maxmin速度。 CAST(m.date as DATE)删除了datetime

的时间部分
SELECT CAST(d.date as DATE) as date,
       MAX(d.speed) AS maxSpeed,
       AVG(d.speed) AS avgSpeed
  FROM Driver as d
 WHERE d.date between '2014-01-01 09:00:00.491' and
       '2014-03-11 17:00:00.491'
 GROUP BY CAST(d.date as DATE)
 ORDER BY date DESC

我的问题是,我想从d中选择一些其他字段(如userID,username等)。如果我修改查询以包含其他字段,如下所示:

SELECT CAST(d.date as DATE) as date,
       MAX(d.speed) AS maxSpeed,
       AVG(d.speed) AS avgSpeed,
       d.userId
  FROM Driver as d
 WHERE d.date between '2014-01-01 09:00:00.491' and
       '2014-03-11 17:00:00.491'
 GROUP BY CAST(d.date as DATE)
 ORDER BY date DESC

我收到此错误:

d.userId is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

因此,我将d.userId添加到GROUP BY子句中,当然,我的数据会发生变化,现在每个日期会包含多个条目。

所以,我的问题是如何选择其他字段,同时仍保留我想要的原始数据(每个唯一日期minmax)?

1 个答案:

答案 0 :(得分:1)

如果您要从Driver中选择行以及max()的{​​{1}}和avg()值,请使用窗口函数:

speed

编辑:

如果您希望每个驱动程序每行一行,请使用简单的SELECT d.*, CAST(d.date as DATE) as date, MAX(d.speed) OVER (PARTITION BY CAST(d.date as DATE)) AS maxSpeed, AVG(d.speed) OVER (PARTITION BY CAST(d.date as date)) AS avgSpeed FROM Driver as d WHERE d.date between '2014-01-01 09:00:00.491' and '2014-03-11 17:00:00.491' ORDER BY date DESC;

group by

如果您想添加其他列,则需要将它们添加到SELECT d.userId, CAST(d.date as DATE) as date, MAX(d.speed) as maxSpeed, AVG(d.speed) as avgSpeed FROM Driver as d WHERE d.date between '2014-01-01 09:00:00.491' and '2014-03-11 17:00:00.491' GROUP BY d.userId, CAST(d.date as DATE) ORDER BY date DESC; select