Nested MySQL Query w/ concat and adddate - mysql

I am trying to nest a few queries but so far am getting back error 1242: Subquery returns more than 1 row. I want more than one row, as I am working on a number of records.
I have 2 tables. One has a commencement date stored in 3 columns; yr_comm, mth_comm, day_comm. The 2nd table has a period of service (in years) for a number of users which is expressed as an integer (2.71, 3.45, etc).
I need to take this start date (from table 1), and add on the period of service (from table 2) to obtain an end date, but I only need to display the year.
I have 2 queries which work just fine when seperate, they result in the required values, however I am having trouble combining the queries to get the desired end result.
Query 1: Concatenate the 3 commencement values into date format
SELECT concat_ws('-', yr_comm, mth_comm, day_comm) AS date_comm
FROM table 1
Query 2: Convert the integer yrs_service into days
SELECT format(yrs_served * 365, 0) AS days_served
FROM table 2
Query 3: Use date_add function to add the days service to the commencement date
SELECT date_add(date_comm, INTERVAL days_served DAY) AS date_left
Can anyone suggest how I can achieve the above? Many thanks in advance.
EDIT - Here is the full query I am working on:
SELECT prime_minister.pm_name, yr_comm, party, ADDDATE(
(SELECT CONCAT_WS('-', yr_comm, mth_comm, day_comm) FROM ministry), INTERVAL
(SELECT FORMAT(yrs_served * 365, 0) FROM prime_minister) YEAR) AS date_left
FROM ministry JOIN prime_minister USING (pm_name)
WHERE party NOT LIKE '%labor%'
AND prime_minister.pm_name = ministry.pm_name
ORDER BY pm_name;

you can use user variables
SET #date = CONCAT_WS('-', 2012,1,1); -- paste your query here
SET #toAdd = (SELECT MONTH(CURDATE())); -- paste your query here
SELECT DATE_ADD(#date, INTERVAL #toAdd DAY) AS date_left
SQLFiddle Demo
which is the same as
SET #date = CONCAT_WS('-', 2012,1,1); -- paste your query here
SET #toAdd = (SELECT MONTH(CURDATE())); -- paste your query here
SELECT #date + INTERVAL #toAdd DAY AS date_left
SQLFiddle Demo
or without using variable, which is more longer,
SELECT (CONCAT_WS('-', 2012,1,1)) + INTERVAL (SELECT MONTH(CURDATE())) DAY AS date_left
SQLFiddle Demo

Related

TIMESTAMPDIFF, multiple row results on new column

I have a student database which has a date of enrolment column. I need to run a query on sql that lets look up this date and today's date, and display the difference in yy Years mm Months.
I'm using TIMESTAMPDIFF to work out the difference between these dates but can only produce one value, how can I adapt it to work it out for the entire row? i need to create a new column with this data.
This is the query:
SELECT TIMESTAMPDIFF(MONTH, CURDATE(), (SELECT time_enrolled FROM student) )
AS newDate
If I add a "where" statement at the end i get the specified id for example:
SELECT TIMESTAMPDIFF(MONTH, CURDATE(), (SELECT time_enrolled FROM student WHERE f_id = 4) )
AS newDate
Don't use a subquery. Your original query should be:
SELECT TIMESTAMPDIFF(MONTH, CURDATE(), time_enrolled) AS newDate
FROM student;
The subquery will generate an error if it returns more than one row in a scalar context -- such as returning a value in the select statement.
You can add an appropriate where clause to this query if you like.
EDIT:
To get years and months, use modulo arithmetic:
SELECT floor(TIMESTAMPDIFF(MONTH, CURDATE(), time_enrolled) / 12) as years,
mod(TIMESTAMPDIFF(MONTH, CURDATE(), time_enrolled), 12) as months
FROM student;

Perform date and time calculation within subquery in insert statement

Anyone able to suggest how I could insert the current date + rental period in one query? The syntax in the code block doesn't work but DATE_ADD(NOW(),INTERVAL 1 DAY) works. I am trying to get the integer in INTERVAL to be based on the rental_period. I can do this with multiple queries but I am trying to do one (if possible).
INSERT INTO rental_details (rental_due_date, vg_id, rental_id) SELECT DATE_ADD(
NOW(), INTERVAL rental_period DAY), vg_id, 1 FROM status INNER JOIN video_games as vg ON
vg.status_id = status.status_id WHERE vg_id = 3;
Thanks.
This works but I need current date + rental_period (rental_period is an integer representing the days to add to current date):
INSERT INTO rental_details (rental_due_date, vg_id, rental_id) select rental_period,
vg_id, 1 from status inner join video_games as vg on vg.status_id = status.status_id
where vg_id = 3;
Your syntax appears to be correct. So, it is probably something about the data-type of your columns. You have not provided the details, but the following works:
create table vg_status
( rental_period integer);
create table rental_details
(due_date date);
insert into vg_status values (3);
insert into vg_status values (300);
insert into rental_details
select date_add(now(), interval rental_period day)
from vg_status
select *
from rental_details
You can see the output in SQL Fiddle

How to solve this "cursor" type query in MySQL?

I have the following data in my table. BTW ... this is a DD/MM/YYYY format:
Date
18/09/2012
17/09/2012
13/09/2012
11/09/2012
10/09/2012
09/09/2012
25/08/2012
24/08/2012
The result what I want are:
Date
18/09/2012
13/09/2012
11/09/2012
09/09/2012
25/08/2012
The rule:
It starts from the latest date (18/09/2012) and check the next one down (17/09/2012). If there is a date then removed that from the list because it requires to have 1 day apart. Then goes to 13/09/2012 and then check 12/09/2012 and didn't find and then move to next one so on and so on. Basically you can't have date close each other (min 1 day apart).
Now I can do this on cursor if it's on TSQL however since I'm working on MySQL, is there any such thing in MySQL? Or perhaps any sub-queries approach that can solve this query?
I'm appreciated your feedback.
Try this solution -
SELECT date FROM (
SELECT
date, #d := IF(#d IS NULL OR DATEDIFF(#d, date) > 1, date, #d) start_date
FROM
dates,
(SELECT #d:=null) t
ORDER BY
date DESC
) t
WHERE start_date = date
The subquery finds out start days (18, 13, 11...), then WHERE condition filters records. Try to run the subquery to understand how it works -
SELECT
date, #d := IF(#d IS NULL OR DATEDIFF(#d, date) > 1, date, #d) start_date
FROM
dates,
(SELECT #d:=null) t
ORDER BY
date DESC
SELECT
"MyTable1"."Date"
FROM
"MyTable" AS "MyTable1"
LEFT JOIN "MyTable" AS "MyTable2" ON
ADDDATE("MyTable1"."Date", INTERVAL 1 DAY) = "MyTable2"."Date"
WHERE
"MyTable2"."Date" IS NULL
ORDER BY
"MyTable1"."Date" DESC
As long as I know about mysql query will be quit tricky and buggy if some how you manage to write the one. I suggest go for cursor, here is the syntax of the cursor,
here is the syntax of the cursor

Padding MYSQL data with missing dates when comparing year over year stats?

I have a table that tracks emails sent. It is pretty simple.
ID | DATETIME | E-MAIL | SUBJECT | MESSAGE
I have been collecting data for several years. Some days I don't have any entries in the table.
query1:
SELECT COUNT(ID) FROM emails
WHERE DATE(datetime) >= 'XXXX-XX-XX'
AND DATE(datetime) is <= 'ZZZZ-ZZ-ZZ'
GROUP BY DATE(datetime)
I then use a some php to get one year prior for both XXXX and YYYY and run the second query which is the same as the first...
query2:
SELECT COUNT(ID) from emails
WHERE DATE(datetime) >= 'XXXX-XX-XX'
AND DATE(datetime) is <= 'ZZZZ-ZZ-ZZ'
GROUP BY DATE(datetime)
I am using a charting package to compare how many emails I got for a date range and then I overlay how many emails I got for the same range only one year prior. This is two queries right now and I chart the results.
The issue is where mysql does not have any emails for 2011 for a day in question, but has a few in 2012 for the same day.
Combining the results and graphing them skews the results since I am missing a date and a 0 value for last year for that day, effectively making all my values no longer match up.
2011-03-01 10 2012-03-01 4
2011-03-02 4 2012-03-02 2
2011-03-03 6 2012-03-04 1 <---- see where the two queries
end up diverging? (I had nothing
logged for 2012-03-03 so naturally
it was not in the results.
Is there a way I can get mysql to output the data I need including dates where value appear in one year but not another OR if no values appear in either year (still need date and 0) so my chart works?
I cannot seem to figure out how to do this...
Thanks!
There are a few different ways to get the results for a contiguous set of dates. My favourite one is to create the full set that is required using a dummy table or an existing contiguous set of ids from an AI PK. Something like this -
SELECT '2011-01-01' + INTERVAL (id -1) DAY
FROM dummy
WHERE id BETWEEN 1 AND 365
This will return a full set of days for 2011 which can then be LEFT JOINed to your emails table to get the counts -
SELECT `dates`.`date`, COUNT(emails.id)
FROM (
SELECT '2011-01-01' + INTERVAL (id - 1) DAY AS `date`, '2011-01-01 23:59:59' + INTERVAL (id - 1) DAY AS `end_of_day`
FROM dummy
WHERE id BETWEEN 1 AND 365
) `dates`
LEFT JOIN emails
ON `emails`.`datetime` BETWEEN `dates`.`date` AND `dates`.`end_of_day`
GROUP BY `dates`.`date`
To populate your dummy / seq table you can insert the first ten values manually and then use INSERT ... SELECT to add the rest -
CREATE TABLE dummy (id INTEGER NOT NULL PRIMARY KEY);
INSERT INTO dummy VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
SET #tmp := (SELECT MAX(id) FROM dummy) + 1;
INSERT INTO dummy
SELECT #tmp + id
FROM dummy;
You need to execute the SET query before each run of the INSERT ... SELECT query.

MySQL: Find Missing Dates Between a Date Range

I need some help with a mysql query. I've got db table that has data from Jan 1, 2011 thru April 30, 2011. There should be a record for each date. I need to find out whether any date is missing from the table.
So for example, let's say that Feb 2, 2011 has no data. How do I find that date?
I've got the dates stored in a column called reportdatetime. The dates are stored in the format: 2011-05-10 0:00:00, which is May 5, 2011 12:00:00 am.
Any suggestions?
This is a second answer, I'll post it separately.
SELECT DATE(r1.reportdate) + INTERVAL 1 DAY AS missing_date
FROM Reports r1
LEFT OUTER JOIN Reports r2 ON DATE(r1.reportdate) = DATE(r2.reportdate) - INTERVAL 1 DAY
WHERE r1.reportdate BETWEEN '2011-01-01' AND '2011-04-30' AND r2.reportdate IS NULL;
This is a self-join that reports a date such that no row exists with the date following.
This will find the first day in a gap, but if there are runs of multiple days missing it won't report all the dates in the gap.
CREATE TABLE Days (day DATE PRIMARY KEY);
Fill Days with all the days you're looking for.
mysql> INSERT INTO Days VALUES ('2011-01-01');
mysql> SET #offset := 1;
mysql> INSERT INTO Days SELECT day + INTERVAL #offset DAY FROM Days; SET #offset := #offset * 2;
Then up-arrow and repeat the INSERT as many times as needed. It doubles the number of rows each time, so you can get four month's worth of rows in seven INSERTs.
Do an exclusion join to find the dates for which there is no match in your reports table:
SELECT d.day FROM Days d
LEFT OUTER JOIN Reports r ON d.day = DATE(r.reportdatetime)
WHERE d.day BETWEEN '2011-01-01' AND '2011-04-30'
AND r.reportdatetime IS NULL;`
It could be done with a more complicated single query, but I'll show a pseudo code with temp table just for illustration:
Get all dates for which we have records:
CREATE TEMP TABLE AllUsedDates
SELECT DISTINCT reportdatetime
INTO AllUsedDates;
now add May 1st so we track 04-30
INSERT INTO AllUsedData ('2011-05-01')
If there's no "next day", we found a gap:
SELECT A.NEXT_DAY
FROM
(SELECT reportdatetime AS TODAY, DATEADD(reportdatetime, 1) AS NEXT_DAY FROM AllUsed Dates) AS A
WHERE
(A.NEXT_DATE NOT IN (SELECT reportdatetime FROM AllUsedDates)
AND
A.TODAY <> '2011-05-01') --exclude the last day
If you mean reportdatetime has the entry of "Feb 2, 2011" but other fields associated to that date are not present like below table snap
reportdate col1 col2
5/10/2011 abc xyz
2/2/2011
1/1/2011 bnv oda
then this query works fine
select reportdate from dtdiff where reportdate not in (select df1.reportdate from dtdiff df1, dtdiff df2 where df1.col1 = df2.col1)
Try this
SELECT DATE(t1.datefield) + INTERVAL 1 DAY AS missing_date FROM table t1 LEFT OUTER JOIN table t2 ON DATE(t1.datefield) = DATE(t2.datefield) - INTERVAL 1 DAY WHERE DATE(t1.datefield) BETWEEN '2020-01-01' AND '2020-01-31' AND DATE(t2.datefield) IS NULL;
If you want to get missing dates in a datetime field use this.
SELECT CAST(t1.datetime_field as DATE) + INTERVAL 1 DAY AS missing_date FROM table t1 LEFT OUTER JOIN table t2 ON CAST(t1.datetime_field as DATE) = CAST(t2.datetime_field as DATE) - INTERVAL 1 DAY WHERE CAST(t1.datetime_field as DATE) BETWEEN '2020-01-01' AND '2020-07-31' AND CAST(t2.datetime_field as DATE) IS NULL;
The solutions above seem to work, but they seem EXTREMELY slow (taking possibly hours, I waited for 30 min only) at least in my database.
This clause takes less than a second in same database (of course you need to repeat it manually dozen times and possibly change function names to find the actual dates). pvm = my datetime, WEATHER = my table.
mysql> select year(pvm) as _year,count(distinct(date(pvm))) as _days from WEATHER where year(pvm)>=2000 and month(pvm)=1 group by _year order by _year asc;
--ako