Table : (Employee)
I need to get Data Between two Days I'm using the following query to get data between two dates
SELECT * FROM employee WHERE Price ((DATE('2020-01-01') BETWEEN DATE(start_date) AND DATE(end_date)) OR (DATE('2020-01-03') BETWEEN DATE(start_date) AND DATE(end_date)) OR (DATE(start_date) >= DATE('2020-07-03')) AND DATE(end_date) <= DATE('2020-07-03'));
I Got the following Result :
But I Expect the Following result
So, How can i get my expected result data in mysql
Your query seems to have nothing to do with your sample data.
Based on your data, you seem to need to generate the dates. You can do this using a recursive CTE and then join:
with recursive dates as (
select date('2020-01-01') as dte
union all
select dte + interval 1 day
from dates
where dte < date('2020-01-04')
)
select d.dte, e.end_date, e.employeename
from employee e join
dates d
on d.dte between e.start_date and e.end_date
Here is a db<>fiddle.
Related
I want for each group id to get the latest week's worth of data. Not from a specific date, but counting backwards from the MAX(startTime) of each individual group.
However, the following does not seem to work. I assume it's because startTime in each group (a single value) is BETWEENed by itself? Otherwise, how do I keep it in my filter?
SELECT
id
, startTime
FROM MyTable
GROUP BY id, startTime
HAVING startTime BETWEEN MAX(startTime) - INTERVAL 1 WEEK AND MAX(startTime)
What's the right query?
Also, in my case it has to work with MySQL 5.7.
SELECT m.id, m.startTime
FROM (
SELECT id, MAX(startTime) AS startTime
FROM MyTable GROUP BY id
) AS x
JOIN MyTable AS m ON m.id = x.id
AND m.startTime BETWEEN x.startTime - INTERVAL 1 WEEK AND x.startTime;
I expect this query to give me the avg value from daily active users up to date and grouped by month (from Oct to December). But the result is 164K aprox when it should be 128K. Why avg is not working? Avg should be SUM of values / number of current month days up to today.
SELECT sq.month_year AS 'month_year', AVG(number)
FROM
(
SELECT CONCAT(MONTHNAME(date), "-", YEAR(DATE)) AS 'month_year', count(distinct id_user) AS number
FROM table1
WHERE date between '2020-10-01' and '2020-12-31 23:59:59'
GROUP BY EXTRACT(year_month FROM date)
) sq
GROUP BY 1
Ok guys thanks for your help. The problem was that on the subquery I was pulling the info by month and not by day. So I should pull the info by day there and group by month in the outer query. This finally worked:
SELECT sq.day_month, AVG(number)
FROM (SELECT date(date) AS day_month,
count(distinct id_user) AS number
FROM table_1
WHERE date >= '2020-10-01' AND
date < '2021-01-01'
GROUP BY 1
) sq
GROUP BY EXTRACT(year_month FROM day_month)
Do not use single quotes for column aliases!
SELECT sq.month_year, AVG(number)
FROM (SELECT CONCAT(MONTHNAME(date), '-', YEAR(DATE)) AS month_year,
count(distinct id_user) AS number
FROM table1
WHERE date >= '2020-10-01' AND
date < '2021-01-01'
GROUP BY month_year
) sq
GROUP BY 1;
Note the fixes to the query:
The GROUP BY uses the same columns as the SELECT. Your query should return an error (although it works in older versions of MySQL).
The date comparisons have been simplified.
No single quotes on column aliases.
Note that the outer query is not needed. I assume it is there just to illustrate the issue you are having.
RDBMS: MySQL
The time column(s) datatype is of datetime
For every hour of the 24 hour day I need to retrieve the number of rows in which their start_time matches the hour OR the end_time is great than or equal to the hour.
Below is the current query I have which returns the data I need but only based off of one hour. I can loop through and do 24 separate queries for each hour of the day but I would love to have this in one query.
SELECT COUNT(*) as total_online
FROM broadcasts
WHERE DATE(start_time) = '2018-01-01' AND (HOUR(start_time) = '0' OR
HOUR(end_time) >= '0')
Is there a better way of querying the data I need? Perhaps by using group by somehow? Thank you.
Not exactly sure if i am following, but try something like this:
select datepart(hh, getdate()) , count(*)
from broadcasts
where datepart(hh, starttime) <=datepart(hh, endtime)
and cast(starttime as date)=cast(getdate() as date) and cast(endtime as date)=cast(getdate() as date)
group by datepart(hh, getdate())
Join with a subquery that returns all the hour numbers:
SELECT h.hour_num, COUNT(*) AS total_online
FROM (SELECT 0 AS hour_num UNION SELECT 1 UNION SELECT 2 ... UNION SELECT 23) AS h
JOIN broadcasts AS b ON HOUR(b.start_time) = h.hour_num OR HOUR(b.end_time) >= h.hour_num
WHERE DATE(b.start_time) = '2018-01-01'
GROUP BY h.hour_num
I have two tables, which share a key that link the two. Table A has a date column (of the format MM/DD/YYYY), and table B has a date field of the format (YYYY-MM-DD HH:MM:SS).
What I need to do is select all those in table B, that have a key matching table A AND a date field within 30 days of the date field found in table A.
Edit: Both variables are varchars, here is what I currently have (error from using alias formattedEffective in a join). I think the below would work, if I could use aliases in that way.
select *,
DATE_FORMAT(STR_TO_DATE(`Eff_date`, '%m/%d/%Y'), '%Y-%m-%d') as formattedEffective
from `customers`
right join `dispatch` on `customers`.`Member_no` = `dispatch`.`Member_no`
AND `dispatch`.`sortdate` > formattedEffective
AND `dispatch`.`sortdate` < DATE_ADD(formattedEffective,INTERVAL 30 DAY)
What the community is asking for is the ability to create a scenario to give a definitive answer to your question (create table statements, sample data, etc..). The approach below is speculation.
The assumption the query makes is eff_date is a string and sortdate is stored as a MySQL date (i.e., date, datetime, timestamp).
select d.*,
str_to_date(c.eff_date, '%m/%d/%Y') ) as formattedEffective
from customer c
join dispatch d on ( d.member_no = c.member_no
and d.sortdate between str_to_date(c.eff_date, '%m/%d/%Y')
and str_to_date(c.eff_date, '%m/%d/%Y') + interval 30 day );
In case the above answer
does not work, move the matching range to where condition.
select d.*,
str_to_date(c.eff_date, '%m/%d/%Y') ) as formattedEffective
from customer c
join dispatch d on ( d.member_no = c.member_no)
where d.sortdate between str_to_date(c.eff_date, '%m/%d/%Y')
and str_to_date(c.eff_date, '%m/%d/%Y') + interval 30 day );
I have a table with MLSNumber, ListingContractDate, CloseDate.
I want to summarize the activity grouped my month starting with the current month and going back to January 2000.
I have this statement which summarizes the ListingContractDate by month.
SELECT COUNT(MLSNumber) AS NewListings, DATE_FORMAT(ListingContractDate,'%M %Y')
FROM Listings
WHERE Neighbourhood = 'Beachside'
AND ListingContractDate >= '2000-01-01'
GROUP BY YEAR(ListingContractDate), MONTH(ListingContractDate)
ORDER BY ListingContractDate DESC
The two problems with this statement are if there is nothing found in a specific month it skips that month, and I would need to return a 0 so no months are missing, and I am not sure how to get the same count on the CloseDate field or if I just have to run a 2nd query and match the two results up by month and year using PHP.
An exceptionally useful item to have is a "tally table" which simply consists on a set of integers. I used a script found HERE to generate such a table.
With that table I can now LEFT JOIN the time related data to it as shown below:
set #startdt := '2000-01-01';
SELECT COUNT(MLSNumber) AS NewListings, DATE_FORMAT(T.Mnth,'%M %Y')
FROM (
select
tally.id
, date_add( #startdt, INTERVAL (tally.id - 1) MONTH ) as Mnth
, date_add( #startdt, INTERVAL tally.id MONTH ) as NextMnth
from tally
where tally.id <= (
select period_diff(date_format(now(), '%Y%m'), date_format(#startdt, '%Y%m')) + 1
)
) t
LEFT JOIN Temp On Temp.ListingContractDate >= T.Mnth and Temp.ListingContractDate < T.NextMnth
GROUP BY YEAR(T.Mnth), MONTH(T.Mnth)
ORDER BY T.Mnth DESC
Logc,
define a stating date
calculate the number of months from that date until now (using
PERIOD_DIFF + 1)
choose that number of records from the tally table
create period start and end dates (tally.Mnth & tally.NextMnth)
LEFT JOIN the actual data to the tally table using
Temp.ListingContractDate >= T.Mnth and Temp.ListingContractDate < T.NextMnth
group and count the data
see this sqlfiddle`