Add two or more time data values in mysql - mysql

I'm currently working on a project using vb.net and mysql database I just wanna ask how would I be able to sum up 2 or more entries of time in a column in mysql workbench formatted as hh:mm:sec.
For example I have this data stored on my database:
|03:45:00|
|03:12:00|
|03:08:57|
Sample Table
The total should be 10:05:02
I've tried to sum the entire column data using this query but I think I'm doing it wrong.
Select sum(Hours_worked) as Total
from db_project
where
Date_of_entry between '2019-02-04' and '2019-02-15'
order by
Date_of_entry asc;

You can't directly add time values to each other using SUM. Instead, you need to convert them to a value which can be summed (numeric) for example using TIME_TO_SEC. You can then convert the sum back to a time format (using SEC_TO_TIME and TIME_FORMAT) for display:
SELECT TIME_FORMAT(SEC_TO_TIME(SUM(TIME_TO_SEC(Hours_worked))), '%H:%i:%s') AS Total
FROM db_project
WHERE Date_of_entry BETWEEN '2019-02-04' AND '2019-02-15'
Output:
10:06:02
Demo on dbfiddle

Related

Calculate Sum of Mean and Std dev in sql query on single column

I am having table name as "Table1" in mysql.I have to find Sum of Mean and Std dev on column "Open".I did it easily using python but I am unable to do it using sql.
Select * from BANKNIFTY_cal_spread;
Date Current Next difference
2021-09-03 00:00:00 36914.8 37043.95 129.14999999999418
2021-09-06 00:00:00 36734 36869.15 135.15000000000146
2021-09-07 00:00:00 36572.9 36710.65 137.75
2021-09-08 00:00:00 36945 37065 120
2021-09-09 00:00:00 36770 36895.1 125.09999999999854
Python Code-
nf_fut_mean = round(df['difference'].mean())
print(f"NF Future Mean: {nf_fut_mean}")
nf_fut_std = round(df['difference'].std())
print(f"NF Future Standard Deviation: {nf_fut_std}")
upper_range = round((nf_fut_mean + nf_fut_std))
lower_range = round((nf_fut_mean - nf_fut_std))
I search for Sql solution but I didn't get it. I tried building query but it's not showing correct results in query builder in grafana alerting.
Now I added Mean column ,std dev column , upper_range and lower_range column using python dataframe and pushed to mysql table.
#Booboo,
After removing Date from SQL Query, it's showing correct results in two columns- average + std_deviation and average - std_deviation.
select average + std_deviation, average - std_deviation from (
select avg(difference) as average, stddev_pop(difference) as std_deviation from BANKNIFTY_cal_spread
) sq
It looks as though the sample you're using for the aggregations for MEAN, STDDEV, etc is the entire table - in which case you have to drop the DATE field from the query's result set.
You could also establish the baseline query using a CTE (Common Table Expression) using a WITH statement instead of a subquery, and then apply the subsequent processing:
WITH BN_CTE AS
(
select avg(difference) as average, stddev_pop(difference) as std_deviation from BANKNIFTY_cal_spread
)
select average + std_deviation, average - std_deviation from BN_CTE;
With the data you posted having only a single Open column value for any given Date column value, you standard deviation should be 0 (and the average just that single value).
I am having difficulty in understanding your SQL since I cannot see how it relates to finding the sum (and presumably the difference, which you also seem to want) of the average and standard deviation of column Open in table Table1. If I just go by your English-language description of what you are trying to do and your definition of table Table1, then the following should work. Note that since we want both the sum and difference of two values, which are not trivial to calculate, we should calculate those two values only once:
select Date, average + std_deviation, average - std_deviation from (
select Date, avg(Open) as average, stddev_pop(Open) as std_deviation from Table1
group by Date
) sq
order by Date
Note that I am using column aliases in the subquery that do not conflict with built-in MySQL function names.
SQL does not allow both calculating something in the SELECT clause and using it. (Yes, #variables allow in limited cases; but that won't work for aggregates in the way hinted in the Question.)
Either repeat the expressions:
SELECT average(difference) AS mean,
average(difference) + stddev_pop(difference) AS "mean-sigma",
average(difference) - stddev_pop(difference) AS "mean+sigma"
FROM BANKNIFTY_cal_spread;
Or use a subquery to call the functions only once:
SELECT mean, mean-sigma, mean+sigma
FROM ( SELECT
average(difference) AS mean,
stddev_pop(difference) AS sigma
FROM BANKNIFTY_cal_spread
) AS x;
I expect the timings to be similar.
And, as already mentioned, avoid using aliases that are identical to function names, etc.

Fixed starting date but dynamic ending date in MYSQL

I am working with a database that also has its build-in BI tool. My work involves the following stages:
Step 1: Write SQL query (let's suppose I extract two columns, date and average daily revenue)
Step 2: Use the retrieved data to create a visualization
Step 3: Add the visualization to the dashboard
I am writing the following query:
SELECT date, AVG(revenue) as revenue
From table1
Group by date;
I want the dashboard to be dynamic which needs the SQL query to be dynamic first.
The starting date is fixed, Oct 1, 2019 for example, but the ending date should be dynamic i.e. it should capture the data after every one day so that the dashboard gets updated daily.
How should my SQL query look like to achieve this purpose?
Use DATE_ADD to add a day as INTERVAL to start date.
SELECT rev_date,AVG(revenue)
FROM table1
WHERE rev_date BETWEEN "2020-06-15" AND DATE_ADD("2020-06-15",INTERVAL 1 DAY)
GROUP BY rev_date;
PS: Using DATE as column_name is not best practice,DATE being a datatype in MYSQL.

SSRS - match dataset values with hard-coded values

I am trying to create an RDL file and I need a tablix to appear in the following format.
This is how I want the results to look
The values that are in bold are hard coded values. This is how the output from the SELECT statement in the datasets looks
SQL Output
I don't know how to make the values that output from the database match with the hard coded values in the RDL file. The 'Day' field represents a day in the month and the 'Num' field represents the number of sales that were on the day. The above example shows that on the first day of the month, there were 100 sales made. I need the tablix to output in that specific format.
If the day isn't in the SQL output (no sales made that day), I want it to output blank and/or 0.
Any idea how this could be accomplished?
Use a CTE to create rows for each day you need and then join your results on. A starting point for you CTE could be:
;WITH nums AS
(SELECT 1 AS value
UNION ALL
SELECT value + 1 AS value
FROM nums
WHERE nums.value <= 30)
SELECT *
FROM nums
You'll probably then want to modify the total days based on the month you are viewing.
You can do this using lookups, but you would need to hard code a lookup in each cell. e.g. for day 1
=lookup(cint(1),Fields!Day.Value,Fields!Num.Value,"Dataset1")
A faster way would be to create a tablix on the dataset filtered on the first ten days:
=Switch(
Fields!DAY.Value <= 10 and Fields!DAY.Value >=1,"Include",
True,"Exclude"
)
Create a row group on days, then create a column with day and num, and columns with Fields!DAY.Value+10 and Fields!DAY.Value+20 with the following lookups:
=lookup(Fields!DAY.Value+10,Fields!DAY.Value,Fields!NUM.Value,"DataSet1")
=lookup(Fields!DAY.Value+20,Fields!DAY.Value,Fields!NUM.Value,"DataSet1")

Query using LIKE clause with a date string

I work for a gun club and we are trying to find the total number of targets shot at during a specific year. The table contains totals from years 2000-2018 and I am trying to write a query that will look at the string for the date of the shoot which is in a format like this 2010-06-13 00:00:00.000 I just care about the year so I created this query:
SELECT SUM(ShotAt) AS TotalTargets
FROM MemberShootsC
WHERE GunClubNumber = 210015 AND ShootDate LIKE '2007-%%-%% 00:00:00.000'
If I run the query up to the AND clause it works and returns a total. However, I get a null value if I highlight the whole thing. I have tried variations of the string as well. Such as this '2007%' and this '2007-- %'
Not sure what I am missing. Any help is appreciated.
Don't convert to string to query for a year, use YEAR() function instead:
SELECT SUM(ShotAt) AS TotalTargets
FROM MemberShootsC
WHERE GunClubNumber = 210015 AND YEAR(ShootDate)=2007 -- MySQL
You could also use a range query
SELECT SUM(ShotAt) AS TotalTargets
FROM MemberShootsC
WHERE GunClubNumber = 210015 AND ShootDate BETWEEN '2007-01-01' AND '2007-12-01 23:59:59.999'
Note: The above assumes that you do not store dates as strings. The function to use depends on RDBMS. In MS SQL Server you would use DATEPART(year, ShootDate) = 2007

Getting week started date using MySQL

If I have MySQL query like this, summing word frequencies per week:
SELECT
SUM(`city`),
SUM(`officers`),
SUM(`uk`),
SUM(`wednesday`),
DATE_FORMAT(`dateTime`, '%d/%m/%Y')
FROM myTable
WHERE dateTime BETWEEN '2011-09-28 18:00:00' AND '2011-10-29 18:59:00'
GROUP BY WEEK(dateTime)
The results given by MySQL take the first value of column dateTime, in this case 28/09/2011 which happens to be a Saturday.
Is it possible to adjust the query in MySQL to show the date upon which the week commences, even if there is no data available, so that for the above, 2011-09-28 would be replaced with 2011/09/26 instead? That is, the date of the start of the week, being a Monday. Or would it be better to adjust the dates programmatically after the query has run?
The dateTime column is in format 2011/10/02 12:05:00
It is possible to do it in SQL but it would be better to do it in your program code as it would be more efficient and easier. Also, while MySQL accepts your query, it doesn't quite make sense - you have DATE_FORMAT(dateTime, '%d/%m/%Y') in select's field list while you group by WEEK(dateTime). This means that the DB engine has to select random date from current group (week) for each row. Ie consider you have records for 27.09.2011, 28.09.2011 and 29.09.2011 - they all fall onto same week, so in the final resultset only one row is generated for those three records. Now which date out of those three should be picked for the DATE_FORMAT() call? Answer would be somewhat simpler if there is ORDER BY in the query but it still doesn't quite make sense to use fields/expressions in the field list which aren't in GROUP BY or which aren't aggregates. You should really return the week number in the select list (instead of DATE_FORMAT call) and then in your code calculate the start and end dates from it.