Couchbase n1ql query for weekly range - couchbase

I am trying to get query based on weekly range.
document structure :
{
type: "city",
createdDate: "2020-08-15T12:00:00"
//other fields
}
Query should count records per week.
output:
date count
2020-08-01 20
2020-08-08 20
It should display for weekly in the current month

Checkout Date functions https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/datefun.html
SELECT date, COUNT(1) AS cnt
FROM mybucket AS d
LET date = DATE_PART_STR(DATE_ADD_STR(d.createdDate, -IMOD(DATE_PART_STR(d.createdDate,"day")-1,7)), "1111-11-11")
WHERE ...........
GROUP BY date;
Note: Last week of the month is partial. Weekly grouping per month is complex because no equal days. Checkout Extracting date components in above link (iso_week, week)

Related

MySQL query daily avg value over years for the same day

I've got a MySQL database filled with weather data, e.g. mean temperature value for every day. I would like query for the average of these values for every day the last five years.
for example:
2019-06-04 20.04
2018-06-04 18.42
2017-06-04 19.21
2016-06-04 21.22
2015-06-04 17.19
query result should be: 19.216
For now I am able to get the avg for a specific day for the last years:
select date, avg(ta) from weatherdata where date like "20%-06-04";
But I am searching for an option to get the avg value for every day in a single query if possible.
Use GROUP BY.
SELECT MONTH(date) AS month, DAY(date) AS day, AVG(ta)
FROM weatherdata
GROUP BY month, day
ORDER BY month, day

MySQL time diff grouped by day

I have a table from which I'm trying to extracted summed timediff information grouped by days. I don't really know if this is possible
Table columns: mode_type, start_time.
A record exists in this table for each time an employee starts or stops a timer. mode_type = 1 for start, mode_type = 0 for stop.
I'd like to return a sum of the seconds used for each day in the last 30 days.
E.g:
date, seconds_used
02/04/2014, 25
03/04/2014, 12415
04/04/2014, 925
Currently I can return a list of seconds used per mode_type and date but this required later calc in PHP.
SELECT
mode_type,
Sum(Unix_Timestamp(start_time)) AS time,
start_time
FROM
activations
WHERE
start_time < Date(Now() + INTERVAL 1 MONTH)
GROUP BY
mode_type, Day(start_time)
ORDER BY
start_time
I'm stuck... is this possible or do I need to do revert to calculating the diff in PHP post request?
Thanks in advance.
Can you try with this:
SELECT DATE(start_time) AS startdate, TIME_TO_SEC(TIMEDIFF(NOW(),start_time)) AS secs
FROM activations
GROUP BY
startdate

Count number of Distinct days in query

We have a table that has a StartDate field which holds a type of datetime. There are thousands of records and I am looking for a way to find the number of days within a given result returned from this table. For instance, if my table had this data:
ID | StartDate
--------------
1 01/01/2013 09:34:54
2 01/01/2013 11:23:21
3 04/11/2013 14:43:23
4 04/11/2013 17:13:03
5 04/25/2013 18:02:59
6 07/21/2013 02:56:12
7 10/01/2013 19:43:10
Then the query should return 5 as the 2 dates on 01/01/2013 count as 1 and the same for 04/11/2013.
The only SQL I've been able to come up with is:
SELECT COUNT(DISTINCT(DATEPART(DAY, StartDate)))
FROM Stats
WHERE StartDate BETWEEN '01/01/2013' AND '12/31/2013' --This is just for filtering
But this returns 4 because it doesn't take the month into account.
Any help is appreciated.
You can CAST as date
SELECT COUNT(DISTINCT CAST(StartDate AS DATE))
FROM Stats
WHERE StartDate >= '20130101' AND StartDate < '20140101'
Also use an unambiguous date format such as yyyymmdd and >= < not BETWEEN.
Your current query would include the 31st December if there was a row with exactly the value 20131231 00:00:00 but not any with different times on that date. I doubt that is intentional.

Writing a function to get days in a range grouped by month and perform some simple calculations on them

I am trying to write a function in mySQL that takes two dates(startDate and endDate) as parameters. It then calculates the days in each month.
The database contains a targetRevenue table that has got the target revenue values for each month and year.
id month year targetRev
25 1 2012 1000.00
26 2 2012 5000.00
27 3 2012 8000.00
The function finds the revenue for a month based on the number of days in it and then returns the total.
Example : startDate : 2012-01-19 endDate : 2012-03-24
Function returns [ targetRev(19 days in Jan) + targetRev(29 days Feb) + targetRev(24days in March)]
I am new to writing functions in mysql , so a little bit of help to get me started would be very useful. Thanks in advance!
If instead of your month and year columns, you represented the month of each record in your targetRevenue table by a DATE column containing the first day of each month:
ALTER TABLE targetRevenue
ADD COLUMN first DATE;
UPDATE targetRevenue
SET first = STR_TO_DATE(CONCAT_WS('-', year, month, 1), '%Y-%c-%e');
ALTER TABLE targetRevenue
DROP COLUMN year,
DROP COLUMN month;
You could then obtain the total target revenue for your project (assuming it is inclusive of both start and end date) with:
-- calculate the summation of
SELECT SUM(CONVERT(
-- number of project days in month...
GREATEST(0,
-- ...is calculated as the difference between...
DATEDIFF(
-- ...the last day of the project in this month...
LEAST('2012-03-24', LAST_DAY(first)),
-- ...and the first day of the project in this month...
GREATEST('2012-01-19', first)
)
-- ...plus one because first and last project days were inclusive
+ 1
)
-- multiply by the target revenue for this month
* targetRev
-- divide by the number of days in the month
/ DAY(LAST_DAY(first)),
-- convert result to fixed-point format, to two d.p.
DECIMAL(11,2)
)) AS total
FROM targetRevenue
-- only perform for months in which the project was active
WHERE '2012-01-19' <= LAST_DAY(first) AND first <= '2012-03-24'
See it on sqlfiddle.
If you can't change the schema, you could replace references to first with the value to which that column was updated above.
For this you can use SUM() function like:
SELECT SUM(targetRev) from your_table
WHERE date_column BETWEEN your_startDate_column AND your_endDate_column;
you need not to calculate days of each month..
Use this query like this
SELECT SUM(targetRev), MONTH(date_column) as mo
from your_table
WHERE date_column BETWEEN your_startDate AND your_endDate
GROUP BY mo;
This will give the result for each month total revenue (use like this logic)
If it is two different years you can use like
concat(year(date_column),month(date_column)) as mo

mysql get current date and row date

Is it possible to do sql query on what day is today and get the row of today for date column?
So let say today is july 25th, i have database table sales, column name date, date = sales transaction date in timestamp.
i need all row that the sales date is same with current date and also is it possible set value as gmt+5?
This will get you all the rows for today's date:
SELECT * FROM sales
WHERE DATE(NOW()) = DATE(DATE_ADD(sales_transaction, INTERVAL 5 HOUR))
ORDER BY sales_transaction
As for GMT +5, Do you mean all rows with a sales date +5 hours or today +5 hours?
EDIT: Updated to add 5 hours to sales date. For a column called date, I would use the back-ticks to indicate it's a column name. e.g. SELECT `date`` FROM sales
I can't figure out how to work the back-ticks on the date field. But you should get the idea. Wrap your column names with `
Give some time and Check out Date Time Function of mySQL
SELECT * FROM tablename WHERE salesdate = '1998-1-1';
If your date is stored in GMT timezone
Select *
FROM tablename
WHERE DATE_ADD(NOW(), INTERVAL 5 HOUR) = salesdate
SELECT * FROM `sales` WHERE DAYOFMONTH(FROM_UNIXTIME(date)) = DAYOFMONTH(DATE(now()))
seems working.
Thank you for all of your replies.