I am working on a sql view that should get the average number of hits by hour of the day, regardless of what day/date it is for traffic monitoring (12:00:00.000 - 12:59:59.999). Any ideas?
EDIT
Now I have the total, how do I get the average? SELECT AVG("FUNCTION BELOW") DOES NOT WORK
SELECT COUNT(*) AS total, DATEPART(hh, LogDate) AS HourOfDay
FROM dbo.Log
GROUP BY DATEPART(hh, LogDate)
Convert to DATEPART(hh,.....
Example SELECT DATEPART(hh,GETDATE())
Since you are on SQL Server 2008, you can use the time data type, just convert to time
example
SELECT CONVERT(TIME,GETDATE())
Then you can filter that also
Since I am not sure what your output is supposed to be like I am showing you both, but if all you need is to group by hour, then just do a datepart(hh.....
The query below may be good enough for you. It divides the count by the difference between todays date and the minimum date in the LogDate column.
SELECT DATEPART(hh,LogDate) as Hour
,CAST(COUNT(*)as decimal)/DATEDIFF(d,(SELECT MIN(LogDate) from log)
,CURRENT_TIMESTAMP) as AverageHits
, COUNT(*) as Count
FROM log
GROUP BY DATEPART(hh,LogDate)
ORDER by DATEPART(hh,LogDate) asc
Related
I want to get how many times a pack has been used in any given month, Each time the pack is activated it can be used for 7 days.
Expected Result
I have tried Lag and lead along with nesting the query.
Here's what you need.
select
max([Date]) as Month_END,
Line_Number,
Pack_Code,
Product_Code,
count(1) as [Number Of Packs]
from
Table
group by
datepart(mm, [Date]),
Line_Number,
Pack_Code,
Product_Code
Some issue with my laptop. Before i complete my answer, it has posted my response :).
My previous answer will give you the total number of times in a month a pack has been used under count variable. You can then divide the aggregated value by 7 to identify the number of active packs. Hope it helps
You can try converting the date to year month using the below syntax and then apply a group by on the required columns to get the count of the pack_code
to_char(to_Date(LOADED_DT,'YYYY-MM-DD HH24:MI:SS'),'YYYYMM') year_month
Sample query:
select a.year_month,a.line_number,a.pack_code,a.product_code,count(a.pack_code)
select to_char(to_Date(LOADED_DT,'YYYY-MM-DD HH24:MI:SS'),'YYYYMM') year_month,line_number,pack_code,product_code,count(pack_code)
from <table_name> ) a
group by a.year_month,a.line_number,a.pack_code,a.product_code;
I have Climate data stored in table such as (Temperature,Humidity,CO2,Save_Timestamp) in realtime.
How can i write a sql to select average of data by every hour of the day
because when i do full select and render it on html5 with Chart.js
It's BOOM!!
try Something like this
For avg for current date by hour:
select hour(Save_Timestamp) HourSave,
avg(Temperature) avgTemperature, avg(Humidity) avgHumidity, avg(CO2) avgCO2
from yourtable
where date(Save_Timestamp)=current date
group by hour(Save_Timestamp)
For avg for all date by hour:
select date(Save_Timestamp) DateSave, hour(Save_Timestamp) HourSave,
avg(Temperature) avgTemperature, avg(Humidity) avgHumidity, avg(CO2) avgCO2
from yourtable
group by date(Save_Timestamp) , hour(Save_Timestamp)
SELECT CONVERT(VARCHAR(10),Save_Timestamp,112) AS Date,
DATEPART(hh,Save_Timestamp) AS Hour,
SUM(TEMPERATURE)/COUNT(*) AS AvgTemp
FROM CLIMATE_TABLE
GROUP BY
CONVERT(VARCHAR(10),Save_Timestamp,112),
DATEPART(hh,Save_Timestamp)
This might get you what you are looking for.
I have a table as shown above, every 10 minutes a record for each ChannelID is put in the table.
I want to get the max, min and avg for each day for each channel, is this possible?
I am using MS SQL Server 2012
It looks like you know what to do, so I'm guessing the only thing you are missing is that you need to trunc your time value from your date, so each day will be recognized as a group. You can do it by using CAST AS DATE
SELECT cast([dateTime] as date) as Your_Date,ChannelID,
max(reading) as max_reading,
min(reading) as min_reading,
avg(reading) as avg_reading
FROM YourTable
GROUP BY cast([dateTime] as date) ,ChannelID
Hi I have a weather database in SQL Server 2008 that is filled with weather observations that are taken every 20 minutes. I want to get the weather records for each hour not every 20 minutes how can I filter out some the results so only the first observation for each hour is in the results.
Example:
7:00:00
7:20:00
7:40:00
8:00:00
Desired Output
7:00:00
8:00:00
To get exactly (less the fact that it's an INT instead of a TIME; nothing hard to fix) what you listed as your desired result,
SELECT DISTINCT DATEPART(HOUR, TimeStamp)
FROM Observations
You could also add in CAST(TimeStamp AS DATE) if you wanted that as well.
Assuming you want the data as well, however, it depends a little, but from exactly what you've described, the simple solution is just to say:
SELECT *
FROM Observations
WHERE DATEPART(MINUTE, TimeStamp) = 0
That fails if you have missing data, though, which is pretty common.
If you do have some hours where you want data but don't have a row at :00, you could do something like this:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY CAST(TimeStamp AS DATE), DATEPART(HOUR, TimeStamp) ORDER BY TimeStamp)
FROM Observations
)
SELECT *
FROM cte
WHERE n = 1
That'll take the first one for any date/hour combination.
Of course, you're still leaving out anything where you had no data for an entire hour. That would require a numbers table, if you even want to return those instances.
You can use a formula like the following one to get the nearest hour of a time point (in this case it's GETUTCDATE()).
SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, 0, GETUTCDATE()) / 60 * 60, 0)
Then you can use this formula in the WHERE clause of your SQL query to get the data you want.
What you need is to GROUP BY your desired time frame, like the date and the hours. Then, you get the MIN value of the timeframe. Since you didn't specify which columns you are using, this is the most generic thing i can give.
Use as filter :
... where DATEPART(MINUTE, DateColumn) = 0
To filter the result for every whole hour, you can set your where clause to check for 00 minute since every whole hour is HH:00:00.
To get the minute part from a time-stamp, you can use DATEPART function.
SELECT *
FROM YOURTABLENAME
WHERE DATEPART(MINUTE, YOURDATEFIELDNAME) = 0
More information on datepart function can be found here: http://www.w3schools.com/sql/func_datepart.asp
I need to get the count of the distinct names per hour in one query in PostgreSQL 9.1
The relevant columns(generalized for question) in my table are:
occurred timestamp with time zone and
name character varying(250)
And the table name for the sake of the question is just table
The occurred timestamps will all be within a midnight to midnight(exclusive) range for one day. So far my query looks like:
'SELECT COUNT(DISTINCT ON (name)) FROM table'
It would be nice if I could get the output formatted as a list of 24 integers(one for each hour of the day), the names aren't required to be returned.
If I understand correctly what you want, you can write:
SELECT EXTRACT(HOUR FROM occurred),
COUNT(DISTINCT name)
FROM ...
WHERE ...
GROUP
BY EXTRACT(HOUR FROM occurred)
ORDER
BY EXTRACT(HOUR FROM occurred)
;
SELECT date_trunc('hour', occurred) AS hour_slice
,count(DISTINCT name) AS name_ct
FROM mytable
GROUP BY 1
ORDER BY 1;
DISTINCT ON is a different feature.
date_trunc() gives you a sum for every distinct hour, while EXTRACT sums per hour-of-day over longer periods of time. The two results do not add up, because summing up multiple count(DISTINCT x) is equal or greater than one count(DISTINCT x).
You want this by hour:
select extract(hour from occurred) as hr, count(distinct name)
from table t
group by extract(hour from occurred)
order by 1
This assumes there is data for only one day. Otherwise, hours from different days would be combined. To get around this, you would need to include date information as well.