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
Related
I have a SQL query that includes a __DATE__ macro. A Python script replaces this macro with the current date and then the statement is executed thus giving one day's worth of data.
For the first item selected, I would like to use tblLabTestResult.CollectionDate instead of __DATE__.
I would like to include the prior 7 days instead of just the current day.
The desired output would be something similar to:
Date,Result,Total
2021-08-28,Detected,5
2021-08-28,Not Detected,9
2021-08-29,Detected,23
2021-08-29,Not Detected,6
2021-08-30,Detected,88
2021-08-30,Not Detected,26
Current query:
SELECT
'__DATE__' as Date,
tblLabTestResult.Result as Result,
Count(tblLabTestResult.Result) as Total
FROM
PncRegDb.dbo.tblLabTestResult as tblLabTestResult
WHERE
tblLabTestResult.TestName like '%cov%'
AND tblLabTestResult.TestName not like '%aoe%'
AND tblLabTestResult.TestName not like '%antibody%'
AND tblLabTestResult.CollectionDate >= '__DATE__'
AND tblLabTestResult.CollectionDate <= '__DATE__ 11:59:59 PM'
GROUP BY
tblLabTestResult.Result;
How can I change my SQL query to accommodate these requirements? I am using MS SQL Server.
You can use DATEADD() function to get the date from 7 days ago and use all dates between date-7days and date. I have updated where condition in your query below:
SELECT
'__DATE__' as Date,
tblLabTestResult.Result as Result,
Count(tblLabTestResult.Result) as Total
FROM
PncRegDb.dbo.tblLabTestResult as tblLabTestResult
WHERE
tblLabTestResult.TestName like '%cov%'
AND tblLabTestResult.TestName not like '%aoe%'
AND tblLabTestResult.TestName not like '%antibody%'
AND tblLabTestResult.CollectionDate between DATEADD(day, -7, '__DATE__') and '__DATE__ 11:59:59 PM'
GROUP BY
tblLabTestResult.Result;
A few points:
Columns that are not aggregated must be in the GROUP BY
You should be passing your date as a parameter
Best to use a half-open interval to compare dates (exclusive end-point), so #endDate is the day after the one you want
Use short, meaningful aliases to make your code more readable
It doesn't make sense to group and aggregate by the same column. If Result is a non-nullable column then Count(Result) is the same as Count(*)
If you want to group by whole days (and CollectionDate has a time component) then replace ltr.CollectionDate with CAST(ltr.CollectionDate AS date) in both the SELECT and GROUP BY
SELECT
ltr.CollectionDate as Date,
ltr.Result as Result,
COUNT(*) as Total
FROM
PncRegDb.dbo.tblLabTestResult as tblLabTestResult
WHERE
ltr.TestName like '%cov%'
AND ltr.TestName not like '%aoe%'
AND ltr.TestName not like '%antibody%'
AND ltr.CollectionDate >= #startdate
AND ltr.CollectionDate < #endDate
GROUP BY
ltr.CollectionDate, ltr.Result;
a noob question.
I want to query my database looking for pageviews for a given page, and i wrote a query that returns the page / number of pageviews daily. How i should change my query to get the same statistics but not daily but mothly?
So instead:
page pv date
/mysite 10 2017-01-01
get
page pv date
/mysite 500 2017-01
my query:
select
date,
hits.page.pagePath as pagePath,
count(totals.pageviews) as pageViews
from Table_DATE_RANGE ([818251235.ga_sessions_] , Timestamp('2016-01-01'), Timestamp('2017-11-01'))
group by 1,2
It's not clear what you are trying to count in your original query, but here is a query that uses standard SQL and performs the grouping on a monthly basis:
#standardSQL
SELECT
DATE_TRUNC(PARSE_DATE('%Y%m%d', date), MONTH) AS month,
hit.page.pagePath,
COUNT(*)
FROM `818251235.ga_sessions_*`,
UNNEST (hits) AS hit
WHERE _TABLE_SUFFIX BETWEEN
'20160101' AND '20181101'
GROUP BY 1, 2;
Edit: fixed to use DATE_TRUNC instead of EXTRACT(MONTH FROM ...) since both the year and month are relevant.
you can use date functions like UTC_USEC_TO_MONTH, UTC_USEC_TO_WEEK, UTC_USEC_TO_DAY to normalize them to the first day of the month, first day of the week.
select
date(UTC_USEC_TO_MONTH(date)) as monthly,
.....
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 want to track the users in my db, when they was created to show it in a awesome chart. Each user has a column "Created" that is the DateTime when they was created. Right down to the time that day.
However, for my chart I dont really care about the time, just the day, month and year. Is there a way I can return a datetime and count when I use datepart as the following:
SELECT datepart(year,Created), datepart(month,Created), datepart(day,Created), COUNT(*) AS COUNT
FROM [dbms].[User]
GROUP BY datepart(year,Created), datepart(month,Created), datepart(day,Created)
This returns three columns for year, month and day. Is there any way I could make it sexy and make it return DateTime (in YYYY/MM/DD format) and the cound?
If you're using SQL Server 2008 or later, you can take advantage of the date data type.
SELECT cast(Created as date), COUNT(*) AS COUNT
FROM [dbms].[User]
GROUP BY cast(Created as date)
If you're using SQL Server 2005 or earlier:
SELECT dateadd(day,datediff(day,0,Created), 0), COUNT(*) AS COUNT
FROM [dbms].[User]
GROUP BY dateadd(day,datediff(day,0,Created), 0)
You can try the following:
SELECT dateadd(day, datediff(day, 0, Created), 0) as date, COUNT(*) AS COUNT
FROM [dbms].[User]
GROUP BY dateadd(day, datediff(day, 0, Created), 0)
This will group you users by the creation date without time and will works on each versions of SQL Server. Among this, the Dateadd operation is more faster that casting...
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