multi sql select statement - mysql

i have a table of this sort:
| name | salary | day | month |
| james | 200.00 | 2 | january |
| marie | 400.00 | 4 | january |
| jimmy | 300.00 | 7 | january |
| Fredd | 700.00 | 3 | february |
| rosieli | 500.00 | 5 | february |
| rosela | 800.00 | 6 | february |
if the table name is 'db_table', how do I write an sql select query to select records from 4th January to 5th February.
something like:
select * from db_table between day='4',month='january' and day='5' and month='february'";
please how do I write a proper sql statement to get the desired results.so that the table looks like this:
| name | salary | day | month |
| marie | 400.00 | 4 | january |
| jimmy | 300.00 | 7 | january |
| Fredd | 700.00 | 3 | february |
| rosieli | 500.00 | 5 | february |
thank you

You'll need to make the day a number but this is it:
SELECT *
FROM db_table
WHERE (day >= 4 and month = 'January')
OR (day <= 5 and month = 'February')
For e.g. January to April:
SELECT *
FROM db_table
WHERE (day >= 4 and month = 'January')
OR (day <= 5 and month = 'April')
OR month IN ('February','March')

You really should do this using dates.
select t.*
from t
where str_to_date(concat_ws(2020, month, day), '%Y %M %d') between '2020-01-04' and '2020-02-05';
When possible, date comparisons should be made using dates.
I used 2020 because it is a leap year, so it will handle February 29th.
Once you've solved this, you should fix your data model to contain an actual date rather than a month/day combination.

how do I write an sql select query to select records from 4th January to 5th February.
select *
from db_table
where (month = 'january' and 4 <= cast(day as int)) or
(month = 'february' and cast(day as int) <= 5)
Note that a table design with separate month and day columns makes querying hard. It would get even harder at year boundaries. A better design would make use of your database's native datetime column type. Then you can query like:
select *
from db_table
where dt_col between '2019-01-04' and '2019-02-05'

You must create a comparable string out of month and day to use in a between statement:
select * from db_table where
concat(case month
when 'january' then '01'
when 'february' then '02'
........................
when 'december' then '12'
end, case when day < 10 then '0' else '' end, day) between '0104' and '0205'
Like this you can compare any date range by modifying only the starting and ending dates.

Related

Group Rows in group by though it contains NULL value in mysql / postgres

I have a table from where I am getting month names and some quantity measures.
Table Name = Month_Name
SELECT month_name,q1,q2 FROM month_name;
mysql> SELECT * FROM MONTH;
+------------+------+------+
| month_name | q1 | q2 |
+------------+------+------+
| January | 10 | 20 |
| March | 30 | 40 |
| March | 10 | 5 |
+------------+------+------+
Expected Output:
mysql> SELECT month_name ,SUM(q1),SUM(q2) FROM MONTH GROUP BY month_name;
+------------+---------+---------+
| month_name | sum(q1) | sum(q2) |
+------------+---------+---------+
| January | 10 | 20 |
| Febuary | 0 | 0 |
| March | 40 | 45 |
| April | 0 | 0 |
+------------+---------+---------+
Group by month will not print February and April since these 2 months are not present in base table. I do not want to use Union All since there will be performance issues with union All, Is there any other optimised approach to this.
You can use a calendar table which keeps track of all the month names which you want to appear in your report.
SELECT
m1.month_name,
SUM(q1) AS q1_sum,
SUM(q2) AS q2_sum
FROM
(
SELECT 'January' AS month_name UNION ALL
SELECT 'February' UNION ALL
SELECT 'March' UNION ALL
...
SELECT 'December'
) m1
LEFT JOIN month m2
ON m1.month_name = m2.month_name
GROUP BY
m1.month_name;
Note that while this solve your immediate problem, it is still not ideal, because we don't have any easy way to sort the months. A much better table design would be to maintain a date column. The month name is easily derived from the date.

mysql sum group by month and date using a contract start and end date

I have a table full of monthly contracts. There is a monthly price, a start date, and an end date for each. I am trying to graph each month's total revenue and am wondering if it's possible to do this in one query (vs. a query for each month).
I know how to group by month and year in mysql, but this requires a more complex solution that "understands" whether to include in the sum for a given month/year based on the start and end date of the contract.
Shorthand example
| contract_id | price | start_date | end_date |
| 1 | 299 | 1546318800 (1/1/19) | 1554004800 (3/31/19) |
| 2 | 799 | 1551416400 (3/1/19) | 1559275200 (5/31/19) |
With this example, there's an overlap in March. Both contracts are running in March, so the sum returned for that month should be 1098.
I'd like to be able to produce a report that includes every month between two dates, so in this case I'd send 1/1/19 - 12/31/19, the full year of 2019 and would hope to see 0 results as well.
| month | year | price_sum |
| 1 | 2019 | 299 |
| 2 | 2019 | 299 |
| 3 | 2019 | 1098 |
| 4 | 2019 | 799 |
| 5 | 2019 | 799 |
| 6 | 2019 | 0 |
| 7 | 2019 | 0 |
| 8 | 2019 | 0 |
| 9 | 2019 | 0 |
| 10 | 2019 | 0 |
| 11 | 2019 | 0 |
| 12 | 2019 | 0 |
Here is a full working script for your problem, which uses a calendar table approach to represent every month in 2019. Specifically, we represent each month using the first of that month. Then, a given price from your table is applicable to that month if there is overlap with the start and end range.
WITH yourTable AS (
SELECT 1 AS contract_id, 299 AS price, '2019-01-01' AS start_date, '2019-03-31' AS end_date UNION ALL
SELECT 2, 799, '2019-03-01', '2019-05-31'
),
dates AS (
SELECT '2019-01-01' AS dt UNION ALL
SELECT '2019-02-01' UNION ALL
SELECT '2019-03-01' UNION ALL
SELECT '2019-04-01' UNION ALL
SELECT '2019-05-01' UNION ALL
SELECT '2019-06-01' UNION ALL
SELECT '2019-07-01' UNION ALL
SELECT '2019-08-01' UNION ALL
SELECT '2019-09-01' UNION ALL
SELECT '2019-10-01' UNION ALL
SELECT '2019-11-01' UNION ALL
SELECT '2019-12-01'
)
SELECT
d.dt,
SUM(t.price) AS price_sum
FROM dates d
LEFT JOIN yourTable t
ON d.dt < t.end_date
AND DATE_ADD(d.dt, INTERVAL 1 MONTH) > t.start_date
GROUP BY
d.dt;
Demo
Notes:
If your dates are actually stored as UNIX timestamps, then just call FROM_UNIXTIME(your_date) to convert them to dates, and use the same approach I gave above.
I had to use the overlapping date range formula here, because the criteria for overlap in a given month is that the range of that month intersects the range given by a start and end date. Have a look at this SO question for more information on that.
My code is for MySQL 8+, though in practice you may wish to create a bona fide calendar table (the CTE version of which I called dates above), which contains the range of months/years which you want to cover your data set.
I understand that you will be given a range of dates for which you will need to report. My solution requires you to initialize a temporary table, such as date_table with the first day of each month for which you want to report on:
create temporary table date_table (
d date,
primary key(d)
);
set #start_date = '2019-01-01';
set #end_date = '2019-12-01';
set #months = -1;
insert into date_table(d)
select DATE_FORMAT(date_range,'%Y-%c-%d') AS result_date from (
select (date_add(#start_date, INTERVAL (#months := #months +1 ) month)) as date_range
from mysql.help_topic a limit 0,1000) a
where a.date_range between #start_date and last_day(#end_date);
Then this should do it:
select month(dt.d) as month, year(dt.d) as year, ifnull(sum(c.price), 0) as price_sum
from date_table dt left join contract c on
dt.d >= date(from_unixtime(c.start_date)) and dt.d < date(from_unixtime(c.end_date))
group by dt.d
order by dt.d
;
Resulting in:
+-------+------+-----------+
| month | year | price_sum |
+-------+------+-----------+
| 1 | 2019 | 299 |
| 2 | 2019 | 299 |
| 3 | 2019 | 1098 |
| 4 | 2019 | 799 |
| 5 | 2019 | 799 |
| 6 | 2019 | 0 |
| 7 | 2019 | 0 |
| 8 | 2019 | 0 |
| 9 | 2019 | 0 |
| 10 | 2019 | 0 |
| 11 | 2019 | 0 |
| 12 | 2019 | 0 |
+-------+------+-----------+
See demo
I am not sure about the semantics of the column end_date. Right now I am comparing the first a follows: start_date <= first_of_month < end_date. Perhaps the test should be start_date <= first_of_month <= end_date, in which case:
dt.d >= date(from_unixtime(c.start_date)) and dt.d < date(from_unixtime(c.end_date))
becomes:
dt.d between date(from_unixtime(c.start_date)) and date(from_unixtime(c.end_date))
With end_date being the last day of the month, it would not matter either way.

mysql return all rows whether data exists or not

Here is a part of table from which I am retrieving data for the last 3 months including current month
+-------------+-----------------------+
| Wo_id | updated_at |
+-------------+-----------------------+
| 1 | 2018-12-05 10:38:06 |
| 2 | 2018-12-02 15:21:17 |
| 3 | 2018-12-01 22:18:53 |
| 4 | 2018-10-25 10:38:06 |
| 5 | 2018-10-18 15:21:17 |
| 6 | 2018-10-16 22:18:53 |
| 7 | 2018-10-19 10:26:19 |
| 8 | 2018-10-27 07:06:52 |
| 9 | 2018-09-25 11:35:09 |
| 10 | 2018-09-18 12:54:27 |
The query I tried is
SELECT MONTHNAME(updated_at) month,YEAR(updated_at) year_name,
MONTH(updated_at) month_no, COUNT(*) work_orders
FROM work_orders where updated_at >= last_day(now()) + interval 1 day - interval 3 month
GROUP by MONTH(updated_at),YEAR(updated_at)
ORDER BY MONTH(updated_at) DESC
The Output I am getting is
+-------------+-------------+----------+-------------+
| month | year_name | month_no | work_orders |
+-------------+-------------+----------+-------------+
| December | 2018 | 12 | 3 |
| October | 2018 | 10 | 5 |
| September | 2018 | 9 | 2 |
As you can see the query is neglecting November as its data is not in the table. It is Including September in order to complete the cycle of 3 months which is wrong. I want the output like this
+-------------+-------------+----------+-------------+
| month | year_name | month_no | work_orders |
+-------------+-------------+----------+-------------+
| December | 2018 | 12 | 3 |
| November | 2018 | 9 | 0 |
| October | 2018 | 10 | 5 |
Can someone guide me in modifying the above mentioned query. Thanks
You need to create a table of the last three months and then LEFT JOIN that to your work orders table (using the month of the work order) to get the results you want. The table of the last 3 months can be generated using a UNION:
SELECT NOW() AS month
UNION
SELECT NOW() - INTERVAL 1 MONTH
UNION
SELECT NOW() - INTERVAL 2 MONTH
Output (as of 2018-12-07):
month
2018-12-07 11:06:15
2018-11-07 11:06:15
2018-10-07 11:06:15
Note that it is OK to subtract 1 month from the date as if the day number is larger than the number of days in the previous month it will be adjusted downward to make the date valid (see the manual).
The final query then becomes:
SELECT MONTHNAME(m.month) AS month_name, YEAR(m.month) AS year_name,
MONTH(m.month) AS month_no, COUNT(wo.Wo_id) work_orders
FROM (SELECT NOW() AS month
UNION
SELECT NOW() - INTERVAL 1 MONTH
UNION
SELECT NOW() - INTERVAL 2 MONTH) m
LEFT JOIN work_orders wo ON MONTH(wo.updated_at) = MONTH(m.month) AND
YEAR(wo.updated_at) = YEAR(m.month)
GROUP by m.month, year_name
ORDER BY m.month DESC
Note that we don't need a WHERE clause as the values in the month table restrict the data to the last 3 months that we are interested in. Also we use a LEFT JOIN so that we get a result for each month even if there were no work orders that month.
Output:
month_name year_name month_no work_orders
December 2018 12 3
November 2018 11 0
October 2018 10 5
Demo on dbfiddle

Select all records that were created on a given day N months ago

Given a table orders:
+-----+---------+-------------------------+
| id | price | created_at |
+-----+---------+-------------------------+
| 1 | 16.50 | 2017-02-28 12:52:00.824 |
| 2 | 22.00 | 2017-10-03 15:12:39.107 |
| 3 | 50.00 | 2017-12-03 12:54:42.658 |
| 4 | 12.00 | 2018-01-02 07:21:47.808 |
| . | . | . |
| . | . | . |
| . | . | . |
+-----+---------+-------------------------+
and current date:
+---------------------+
| NOW() |
+---------------------+
| 2018-01-03 10:33:14 |
+---------------------+
I'd like to select all records that were created on current day any months ago. So for above data my query should return:
+-----+---------+-------------------------+
| id | price | created_at |
+-----+---------+-------------------------+
| 2 | 22.00 | 2017-10-03 15:12:39.107 |
| 3 | 50.00 | 2017-12-03 12:54:42.658 |
+-----+---------+-------------------------+
But there are some edge cases for the last day of month:
if it's 31-days month, it's trivial
if it's 30-days month, the query should return all records created on 30th and 31st day of month
if it's February in a leap year, the query should return all records created on 29th, 30th and 31st day of month
if it's February in a normal year, the query should return all records created on 28th, 29th, 30th and 31st day of month
What I have tried is something like this:
SELECT * FROM orders
JOIN (
SELECT id, PERIOD_DIFF(
DATE_FORMAT(NOW(), "%Y%m"),
DATE_FORMAT(created_at, "%Y%m")
) AS diff
FROM orders
) AS periods
ON orders.id = periods.id
WHERE DATEDIFF(created_at + INTERVAL diff MONTH, NOW()) = 0;
But it doesn't cover the edge cases and I believe there is a smarter way (maybe without a subquery) to achieve the expected results.
EDIT:
To give you more context - what I need is a kind of a loop. I have a cron job scheduled to run once a day at midnight. This job should select all ids of orders that were created on this day any months ago and then refresh some other data associated with those ids. The important part is to refresh this data exactly once every month - that's why the last day of months is so crucial.
For example, given following creation dates:
DATES = [
2015-05-30, 2016-02-29, 2016-10-03,
2016-12-31, 2017-05-28, 2018-01-03
]
+---------------+------------------------------------+
| NOW() | SHOULD BE INCLUDED |
+---------------+------------------------------------+
| 2018-01-03 | 2016-10-03, 2018-01-03 |
| 2018-02-28 | 2016-02-29, 2016-12-31, 2017-05-28 |
| 2018-04-30 | 2015-05-30, 2016-12-31 |
| 2018-10-31 | 2016-12-31 |
+---------------+------------------------------------+
Can I suggest a slight simplification Walerian?
SELECT
*
FROM
orders
WHERE
(
DAYOFMONTH(created_at) = DAYOFMONTH( NOW() ) --monthdays that match
)
OR
(
( DAYOFMONTH( LAST_DAY( NOW() ) ) = DAYOFMONTH( NOW() ) ) --base date is end of month
AND
( DAYOFMONTH(created_at) > DAYOFMONTH( NOW() ) ) --target monthdays are beyond base monthday
)
Incidentally I don't have a MySQL environment, so I'm just taking it on trust that these are the correct functions in MySQL.
Use DAYOFMONTH() function to compare the day of the NOW() and the created_at.
Like this:
SELECT * FROM ORDERS
WHERE (DAYOFMONTH(NOW() < LAST_DAY(NOW()) -- if not last day of month
AND DAYOFMONTH(created_at) = DAYOFMONTH(NOW())
OR (LAST_DAY(NOW()) = DAYOFMONTH(NOW()) -- if last day of month
AND DAYOFMONTH(NOW()) BETWEEN DAYOFMONTH(created_at) AND LAST_DAY(created_at)) --
Inspired by suresubs's answer, I figured out how the query should look like.
SELECT * FROM orders
-- (1)
WHERE (DAYOFMONTH(NOW) < DAYOFMONTH(LAST_DAY(NOW()))
AND DAYOFMONTH(created_at) = DAYOFMONTH(NOW()))
-- (2)
OR (DAYOFMONTH(LAST_DAY(NOW())) = DAYOFMONTH(NOW())
AND DAYOFMONTH(created_at) BETWEEN DAYOFMONTH(NOW()) AND DAYOFMONTH(LAST_DAY(created_at)));
It's using DAYOFMONTH() and LAST_DAY() functions and it's divided into two cases:
Today is not the last day of current month.
Today is the last day of current month.

Format grouped date as readable date

So I have a query that correctly displays the number of registrations for the last 12 months. Here is display:
Registrations per month for last 2 years
1--17
2--12
3--17
4--8
5--9
6--8
7--15
8--20
9--12
10--14
11--13
12--14
But since im running this in say June, the last mont I need to say the readable date May and not '1'. I want instead:
May--17
Apr--12
March--17
.
.
.
Here is my current MYSQL:
SELECT MONTH(create_date) as month , COUNT(create_date) as count
FROM `users`
WHERE create_date >= NOW() - INTERVAL 1 YEAR
GROUP BY MONTH(create_date)
I assumed I just have to use FORMAT_DATE() on the GROUP By as:
GROUP BY FORMAT_DATE(MONTH(create_date, '%M'))
And that would give me my readable month, but the sql statement reports it is not correct. Anyone know how to accomplish this?
Try this:
SELECT DATE_FORMAT(create_date, '%M') AS month, COUNT(create_date) AS count
FROM users
WHERE create_date >= NOW() - INTERVAL 1 YEAR
GROUP BY MONTH(create_date);
The result will be:
+-----------+-------+
| month | count |
+-----------+-------+
| January | 1 |
| February | 1 |
| March | 1 |
| April | 1 |
| May | 2 |
| June | 2 |
| July | 1 |
| August | 1 |
| September | 1 |
| November | 1 |
| December | 1 |
+-----------+-------+
You can use STR_TO_DATE() to convert the number to a date, and then back with MONTHNAME()
SELECT MONTHNAME(create_date(6, '%m')) as month , COUNT(create_date) as count
FROM `users`
WHERE create_date >= NOW() - INTERVAL 1 YEAR
GROUP BY MONTH(create_date)