im trying to take 3 sql queries and insert them into 1 table without getting the null value's and using a group by number as to not get duplicate numbers in the same column.
I have the issue where running query 1 leaves me with a bunch of null data values
and running query 2 doesnt group the numbers resulting in thousands of rows numbers only go up to 100
QUERY 1
insert into table ( number)
select number as 1day from table where date = CURDATE() - interval 1day group by number
insert into table ( number)
select number as 2day from table where date = CURDATE() - interval 1day group by number
insert into table ( number)
select number as 7day from table where date = CURDATE() - interval 1day group by number
so i try to run
QUERY 2
insert into table (number,number,number)
select
*
from
(select number as 1day from test.test where date = curdate() - interval 1 day group by
number) as 1day,
(select number as 2day from test.test where date > curdate() - interval 2 day group by
number) as 2day,
(select number as 7day from test.test where date > curdate() - interval 7 day group
by number) as 7day;
try the below:
insert into table (number,number,number)
select
table.1day,table.2day,table.7day
from
((select number from test.test where date = curdate() - interval 1 day group by
number) as 1day,
(select numberfrom test.test where date > curdate() - interval 2 day group by
number) as 2day,
(select number from test.test where date > curdate() - interval 7 day group
by number) as 7day) as table
select (case one.number when two.number then null else one.number end) as '1day',(case two.number <= third.number when true then (case one.number = two.number when true then null else two.number end) else (case one.number = two.number when false then null else two.number end) end) as '2day',(case (third.number < one.number and third.number = two.number) when true then null else third.number end) as '7day'
from (
(select x.number
from (
(select number,'1day' as 'type' from testtable where date = curdate() - interval 1 day group by number)
union all
(select number,'2day' as 'type' from testtable where date > curdate() - interval 2 day group by number)
union all
(select number,'7day' as 'type' from testtable where date > curdate() - interval 7 day group by number)) as x
where x.type='2day' order by x.number) as two,
(select x.number
from (
(select number,'1day' as 'type' from testtable where date = curdate() - interval 1 day group by number)
union all
(select number,'2day' as 'type' from testtable where date > curdate() - interval 2 day group by number)
union all
(select number,'7day' as 'type' from testtable where date > curdate() - interval 7 day group by number)) as x
where x.type='1day' order by x.number) as one,
(select x.number
from (
(select number,'1day' as 'type' from testtable where date = curdate() - interval 1 day group by number)
union all
(select number,'2day' as 'type' from testtable where date > curdate() - interval 2 day group by number)
union all
(select number,'7day' as 'type' from testtable where date > curdate() - interval 7 day group by number)) as x
where x.type='7day' order by x.number) as third
)
where ((one.number = two.number) or (one.number is null or two.number is null)) or
((third.number = two.number) or (two.number is null or third.number is null))
Related
I have a single line in MySQL table: volunteers
user_id | start_date | end_date
11122 | 2017-04-20 | 2018-02-17
How can I find how many times the 3rd day or 24th day of a month appears? (i.e. 2017-05-03, 2017-06-03, 2017-12-24, 2018-01-24) I'm trying to get to the following count:
Sample Output:
user_id | number_of_third_day | number_of_twenty_fourth_day
11122 | 10 | 10
I look at the documentation online to see if there is a way I can say (pseudo):
SELECT
day, COUNT(*)
FROM volunteers
WHERE day(between(start_date, end_date)) in (3,24)
I tried to create a calendar table to no avail, but I would try to get the days, GROUP BY day, and COUNT(*) times that day appears in the range
WITH calendar AS (
SELECT start_date AS date
FROM volunteers
UNION ALL
SELECT DATE_ADD(start_date, INTERVAL 1 DAY) as date
FROM volunteers
WHERE DATE_ADD(start_date, INTERVAL 1 DAY) <= end_date
)
SELECT date FROM calendar;
Thanks for any help!
This one is more optimized since I generate date range by months not days as other questions, so its faster
WITH RECURSIVE cte AS
(
SELECT user_id, DATE_FORMAT(start_date, '%Y-%m-03') as third_day,
DATE_FORMAT(start_date, '%Y-%m-24') as twenty_fourth_day,
start_date, end_date
FROM table1
UNION ALL
SELECT user_id,
DATE_FORMAT(third_day + INTERVAL 1 MONTH, '%Y-%m-03') as third_day,
DATE_FORMAT(twenty_fourth_day + INTERVAL 1 MONTH, '%Y-%m-24') as twenty_fourth_day,
start_date, end_date
FROM cte
WHERE third_day + INTERVAL 1 MONTH <= end_date
)
SELECT user_id,
SUM(CASE WHEN third_day BETWEEN start_date AND end_date THEN 1 ELSE 0 END) AS number_of_third_day,
SUM(CASE WHEN twenty_fourth_day BETWEEN start_date AND end_date THEN 1 ELSE 0 END) AS number_of_twenty_fourth_day
FROM cte
GROUP BY user_id;
Demo here
A dynamic approach is.
but creating the dateranges, takes a lot of time, so you should have a date table to get the dates
CREATE TABLE table1
(`user_id` int, `start_date` varchar(10), `end_date` varchar(10))
;
INSERT INTO table1
(`user_id`, `start_date`, `end_date`)
VALUES
(11122, '2017-04-20', '2018-02-17')
,(11123, '2019-04-20', '2020-02-17')
;
Records: 2 Duplicates: 0 Warnings: 0
WITH RECURSIVE cte AS (
SELECT
user_id,
`start_date` as date_run ,
`end_date`
FROM table1
UNION ALL
SELECT
user_id,
DATE_ADD(cte.date_run, INTERVAL 1 DAY),
end_date
FROM cte
WHERE DATE_ADD(date_run, INTERVAL 1 DAY) <= end_date
)SELECT user_id,
SUM(DAYOFMONTH(date_run) = 3) as day_3th,
SUM(DAYOFMONTH(date_run) = 24) as day_24th
FROM cte
GROUP BY user_id
user_id
day_3th
day_24th
11122
10
10
11123
10
10
fiddle
In last MySQL version you can use recursion:
-- get list of all dates in interval
with recursive dates(d) as (
select '2017-04-20'
union all
select date_add(d, interval 1 day) from dates where d < '2018-02-17'
) select
-- calculate
sum(day(d) = 10) days_10,
sum(day(d) = 24) days_24
from dates
-- filter 10 & 24 days
where day(d) = 10 or day(d) = 24;
https://sqlize.online/sql/mysql80/c00eb7de69d011a85502fa538d64d22c/
As long as you are looking for days that occur in every month (so not the 29th or beyond), this is just straightforward math. The number of whole calendar months between two dates (exclusive) is:
timestampdiff(month,start_date,end_date) - (day(start_date) <= day(end_date))
Then add one if the start month includes the target day and one if the end month includes it:
timestampdiff(month,start_date,end_date) - (day(start_date) <= day(end_date))
+ (day(start_date) <= 3) + (day(end_date) >= 3)
i have Items table:
item_id | date | item_price |
---------+-------------+--------------
1 | 2022-12-05 | 15 |
2 | 2022-02-14 | 12 |
1 | 2022-11-12 | 50 |
4 | 2022-01-21 | 13 |
1 | 2021-12-12 | 10 |
6 | 2021-12-27 | 83 |
The query which i use to select price one week ago from today's date:
SELECT
items.item_id AS id,
items.item_price AS weekAgoPrice,
items2.item_price AS monthAgoPrice,
FROM
items
LEFT JOIN
items items2 ON items2.item_id = items.item_id
AND items2.date = DATE_SUB(CURDATE(), INTERVAL 30 DAY)
WHERE
items.item_id = '1'
AND items.date = DATE_SUB(CURDATE(), INTERVAL 7 DAY);
How can i modify query that will return the price from the first available date if there is no entry for a particular date. Those, if for the specified item_id there is no price 7 days ago, then it should return the value of 6 days ago, if not 6 then 5. Additionally, if there is no price 1 month ago, it should return value of 29 days ago etc.
You may try with max window function as the following:
With last_prices As
(
Select *,
Max(Case
When date Between DATE_SUB(CURDATE(), INTERVAL 7 DAY) And CURDATE()
Then date
End) Over (Partition By item_id) As last_price_date_week,
Max(Case
When date Between DATE_SUB(CURDATE(), INTERVAL 1 MONTH) And CURDATE()
Then date
End) Over (Partition By item_id) As last_price_date_month
From items
)
Select item_id, date, item_price, 'last week price' As Price_Type
From last_prices
Where item_id = 1 And date = last_price_date_week
Union All
Select item_id, date, item_price, 'last month price' As Price_Type
From last_prices
Where item_id = 1 And date = last_price_date_month
See demo.
If you are open to using a stored procedure, you could make this task more dynamic, have a look at this procedure:
Create Procedure GetLatesPrice(id INT, period INT, interval_type Varchar(1))
Begin
Select item_id, date, item_price
From
(
Select *,
Case
When interval_type='d' Then
Max(
Case
When date Between DATE_SUB(CURDATE(), INTERVAL period Day) And CURDATE()
Then date
End
) Over (Partition By item_id)
When interval_type='m' Then
Max(
Case
When date Between DATE_SUB(CURDATE(), INTERVAL period Month) And CURDATE()
Then date
End
) Over (Partition By item_id)
When interval_type='d' Then
Max(
Case
When date Between DATE_SUB(CURDATE(), INTERVAL period Year) And CURDATE()
Then date
End
) Over (Partition By item_id)
End As last_price_date
From items
) T
Where date = last_price_date And item_id=id;
END
And to execute that procedure for example for item_id=1, 15 days ago:
Call GetLatesPrice(1, 15, 'd');
-- d for days, m for months, y for years
See demo.
If there is no entry for a particular date, you can use the COALESCE function
SELECT
items.item_id AS id,
COALESCE(
items.item_price,
(SELECT items.item_price FROM items WHERE items.item_id = '1' AND items.date = DATE_SUB(CURDATE(), INTERVAL 6 DAY)),
(SELECT items.item_price FROM items WHERE items.item_id = '1' AND items.date = DATE_SUB(CURDATE(), INTERVAL 5 DAY)),
...
) AS price
FROM items
WHERE items.item_id = '1'
SELECT
items.item_id AS id,
COALESCE(
items.item_price,
(SELECT items.item_price FROM items WHERE items.item_id = '1' AND items.date = DATE_SUB(CURDATE(), INTERVAL 6 DAY)),
(SELECT items.item_price FROM items WHERE items.item_id = '1' AND items.date = DATE_SUB(CURDATE(), INTERVAL 5 DAY)),
...
) AS price
FROM items
WHERE items.item_id = '1'
If all you need are scalar values then this would suffice:
SET #ItemID = 1;
SELECT (SELECT item_price FROM items WHERE item_id = #ItemID
AND date1 >= DATE_ADD(CURDATE(), INTERVAL -7 DAY) order by date1 LIMIT 1) as WeekAgoPrice,
etc.
Also see the LATERAL documentation.
Without sample output data it's hard to tell what you intend.
i have query
select a.`2021`,
b.`2022`,
a.product,
concat(ceil((b.`2022`-a.`2021`)/ a.`2021` * 100), '%') as growth
from ( SELECT SUM(total) as `2021`,
product,
sum
FROM table
WHERE YEAR(month) = 2021
AND case when day(CURRENT_DATE()) > 10
then QUARTER(month) = QUARTER(CURRENT_DATE() - INTERVAL 1 MONTH)
else QUARTER(month) = QUARTER(CURRENT_DATE() - INTERVAL 3 MONTH)
end
GROUP BY Product ,
YEAR(month) )a
JOIN ( SELECT SUM(total) as `2022`,
Product
FROM table
WHERE YEAR(month) = 2022
AND case when day(CURRENT_DATE()) > 10
then QUARTER(month) = QUARTER(CURRENT_DATE() - INTERVAL 1 MONTH)
else QUARTER(month) = QUARTER(CURRENT_DATE() - INTERVAL 3 MONTH)
end
GROUP BY Product ,
YEAR(month) ) b on a.Product=b.Product;
if the current date is not the end of the quarter then the data that appears is the data in the previous quarter period
I have a complex mysql query language, including several sub queries and my final result is as below. There is something that I am dealing with it and I can't solve it and this is a way result is being presented. I am wondering to know how can i change the structure of the result in a way that the result is being presented only in one row and I don't want to see NULL fields. I mean something like below
This is mysql query
select count(*) as userRetentionSameDay, null as 'userRetentionDiffDay' from (SELECT date(`timestamp`), `user_xmpp_login`
FROM table1
WHERE DATE(`timestamp` ) = CURDATE() - INTERVAL 1 DAY) as res1
right join (select date(ts), user
from table2
WHERE DATE(ts ) = CURDATE() - INTERVAL 1 DAY
and product_id REGEXP ("^(europe+$" )) as lej1
on lej1.user = res1.`user_xmpp_login`
where res1.`user_xmpp_login` IS not NULL
union all
select null as 'userRetentionSameDay', count(*) as userRetentionDiffDay from (SELECT date(`timestamp`), `user_xmpp_login`
FROM table1
WHERE DATE(`timestamp` ) = CURDATE() - INTERVAL 1 DAY) as res1
right join (select date(ts), user
from table2
WHERE DATE(ts ) = CURDATE() - INTERVAL 1 DAY
and product_id REGEXP ("^(europe+$" )) as lej2
on lej2.user = res1.`user_xmpp_login`
where res1.`user_xmpp_login` IS NULL;
What are the recommended solutions to doing that?
try this.
SELECT A.userRetentionSameDay,B.userRetentionDiffDay FROM (
SELECT COUNT() AS userRetentionSameDay FROM
(
SELECT DATE(timestamp), user_xmpp_login
FROM table1
WHERE DATE(timestamp ) = CURDATE() - INTERVAL 1 DAY) AS res1
RIGHT JOIN (SELECT DATE(ts), USER
FROM table2
WHERE DATE(ts ) = CURDATE() - INTERVAL 1 DAY
AND product_id REGEXP ("^(europe+$" )) AS lej1
ON lej1.user = res1.user_xmpp_login
WHERE res1.user_xmpp_login IS NOT NULL
) A,
(
SELECT COUNT() AS userRetentionDiffDay FROM (
SELECT DATE(timestamp), user_xmpp_login
FROM table1
WHERE DATE(timestamp ) = CURDATE() - INTERVAL 1 DAY
) AS res1
RIGHT JOIN (SELECT DATE(ts), USER
FROM table2
WHERE DATE(ts ) = CURDATE() - INTERVAL 1 DAY
AND product_id REGEXP ("^(europe+$" )
) AS lej2
ON lej2.user = res1.user_xmpp_login
WHERE res1.user_xmpp_login IS NULL
) B;
There is a query which brings back sales data for the last 7 days.
How to get the sales of the last 30 days as well (to see the sales for the last 7 days AND the last 30 days in the results)?
SELECT
a.row_id,
MAX(ad.new_value) - MIN(ad.new_value) AS sales7days
FROM
_audit a
LEFT JOIN _audit_data ad
ON a.audit_id = ad.audit_id
WHERE ad.col = 'sales'
AND a.triggered_datetime > NOW() - INTERVAL 7 DAY
GROUP BY a.row_id
ORDER BY sales7days DESC;
Perhaps with a CASE expression:
SELECT a.row_id
, MAX(case when a.triggered_datetime > NOW() - INTERVAL 7 DAY
then ad.new_value else NULL end)
- MIN(case when a.triggered_datetime > NOW() - INTERVAL 7 DAY
then ad.new_value else NULL end) AS sales7days
, MAX(case when a.triggered_datetime > NOW() - INTERVAL 30 DAY
then ad.new_value else NULL end)
- MIN(case when a.triggered_datetime > NOW() - INTERVAL 30 DAY
then ad.new_value else NULL end) AS sales30days
FROM _audit a, _audit_data ad
WHERE a.audit_id = ad.audit_id AND ad.col = 'sales'
GROUP BY a.row_id;
SELECT
d7.row_id,
d7.salesdays, d30.salesdays
FROM
(
Select a.row_id, MAX(ad.new_value) - MIN(ad.new_value) AS salesdays
From _audit a
LEFT JOIN _audit_data ad ON a.audit_id = ad.audit_id
WHERE ad.col = 'sales' AND a.triggered_datetime > NOW() - INTERVAL 7 DAY
GROUP BY a.row_id
) d7,
(
Select a.row_id, MAX(ad.new_value) - MIN(ad.new_value) AS salesdays
From _audit a
LEFT JOIN _audit_data ad ON a.audit_id = ad.audit_id
WHERE ad.col = 'sales' AND a.triggered_datetime > NOW() - INTERVAL 30 DAY
GROUP BY a.row_id
) d30
where d7.row_id = d30.row_id
ORDER BY sales7days DESC;
assume you want the same row id for both - and either value to show, you may or may not want to make it inner or outer joined and/or COALESCE the value fields (don't know enough about the data).