문제

I'm using MSSQL 2008 R2, and having an issue with the following situation:

With the following query, I will get data I expect (the max and min speed for each date). The CAST(m.date as DATE) removes the time part of my 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

My problem is, I want to select some other fields from d as well (like the userID, username, etc). If I modify the query to include the additional fields, like so:

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

I get this error:

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

So, I add d.userId to the GROUP BY clause, and my data changes, of course, and will now include multiple entries per date.

So, my question is how can I select additional fields, while still maintaining the original data I want (the min and max for each unique date)?

도움이 되었습니까?

해결책

If you want to select rows from Driver along with the max() and avg() values for speed, then use window functions:

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;

EDIT:

If you want one row per driver, per day, then use a simple 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;

If you want to add additional columns, you need to add them both to the select and the group by.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top