简体   繁体   中英

Aggregate by name and average value per day in SQL

I have data of the following format in a table (I have only shown values for two hours, but in reality I have values for all 24 hours):

Name    Availability           Date             ItemID
--------------------------------------------------------
S1          75        2014-11-11 19:00:00.000   1124023
S1          80        2014-11-11 20:00:00.000   1124023
S2          60        2014-11-11 19:00:00.000   1124010
S2          50        2014-11-11 20:00:00.000   1124010

I would like to get the average availability for the entire day in the following format in a view:

Name    Availability       Date     ItemID
--------------------------------------------------------
S1         77.5         2014-11-11  1124023
S2          55          2014-11-11  1124010

It's okay if Date in the output shows up as 2014-11-11 0:00:00.000 as well.

I tried the following, but it doesn't work. Any help would be greatly appreciated.

SELECT Name, AVG(Availability), CAST(FLOOR(CAST(Date AS FLOAT)) AS DATETIME) AS Expr1, ItemID
    FROM dbo.ServiceAvailability
    GROUP BY CAST(FLOOR(CAST(Date AS FLOAT)) AS DATETIME)

Your current query is very close, you are missing a few columns in your GROUP BY clause. I'd also suggest a shorter way to get the date without time.

SELECT 
  Name, 
  AVG(cast(Availability as decimal(10, 2))), 
  CAST([Date] as date) AS Expr1, 
  ItemID
FROM dbo.ServiceAvailability
GROUP BY Name, CAST([Date] as date), ItemID

See Demo . Since you are using SQL Server 2014, you can just cast your datetime column as a date - which drops the time portion. I'd also suggest casting your Availability column to something other than an int so you get a decimal.

Since you are using an aggregate function any columns in the SELECT list that aren't being aggregated need to be included in the GROUP BY clause, so you need to include Name and ItemID .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM