Using a variable/function as a dynamic column name in MySQL - mysql

Is it possible to use a function or a variable as the label for a column in MySQL?
So for example if you wanted to include the date, something like:
select
sum(P.AMOUNT) AS monthname(date_sub(CURDATE(), INTERVAL 1 MONTH))
from
PAYMENT P
WHERE
P.CREATED_DATE > (date_sub(CURDATE(), INTERVAL 1 MONTH));
This fails, as it's not the correct syntax for an AS alias. I've also tried this:
SET #s = monthname(date_sub(CURDATE(), INTERVAL 1 MONTH));
select
sum(P.AMOUNT) AS #s
from
PAYMENT P
WHERE
P.CREATED_DATE > (date_sub(CURDATE(), INTERVAL 1 MONTH));
Which also doesn't work...
Any ideas?
EDIT - With the above example i realize you could actually just use an additional column to return the date info. The problem is i have a few columns with various date ranges, like this:
select
sum(IF((P.CREATED_DATE BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 MONTH) and DATE_SUB(CURDATE(), INTERVAL 0 MONTH)),P.amount,0)) AS 'Month 0',
sum(IF((P.CREATED_DATE BETWEEN DATE_SUB(CURDATE(), INTERVAL 2 MONTH) and DATE_SUB(CURDATE(), INTERVAL 1 MONTH)),P.amount,0)) AS 'Month -1',
sum(IF((P.CREATED_DATE BETWEEN DATE_SUB(CURDATE(), INTERVAL 3 MONTH) and DATE_SUB(CURDATE(), INTERVAL 2 MONTH)),P.amount,0)) AS 'Month -2'
from
PAYMENT P
WHERE
P.AMOUNT < 100000;
So it's the "Month 0" etc i'm looking to replace with a function/query.

Related

SQL comparing date

I want to compare the current date with a date from a database table.
This code:
DATE_FORMAT(dt,'%y-%m')
gives me a date like this 2020-10
and i want that this code:
DATE_ADD(CURRENT_DATE, INTERVAL - 1 month)
gets date like 2020-10 not 2020-10-12(some day)
Here is the whole sql query:
select count(*)
from app_tickets t
where t.status= 3
and DATE_FORMAT(dt,'%y-%m')=DATE_ADD(CURRENT_DATE, INTERVAL - 1 month)
Thanks for help:)
This can make use of indexes
select count(*)
from app_tickets t
where t.status = 3
and t.dt >= DATE_FORMAT(CURRENT_DATE - interval 1 month ,'%Y-%m-01')
and t.dt < DATE_FORMAT(CURRENT_DATE ,'%Y-%m-01')

How can i used less than equal or between function FROM DUAL table?

Im trying to get the date from previous week to current and it seemd between or >= are not working here.
WITH curr_cyc_dt AS (
SELECT BETWEEN TO_DATE ('20181228', 'yyyymmdd') AND TO_DATE ('20190104', 'yyyymmdd') cyc_dt
FROM DUAL
)
set #myDate = CURDATE();
set #rowNumber = 0;
select date_sub(#myDate, interval #rowNumber day),
(#rowNumber := #rowNumber + 1) as rownum
from information_schema.columns
LIMIT 7;
BETWEEN does not work like that, it will not automagically generate a list of dates for you. It is a comparison operator that checks if a date belongs to a date interval.
The simplest way to generate a list of days for the last 7 days (until today included) :
WITH curr_cyc_dt AS (
SELECT
CURDATE(),
DATE_SUB(CURDATE(), INTERVAL 1 DAY),
DATE_SUB(CURDATE(), INTERVAL 3 DAY),
DATE_SUB(CURDATE(), INTERVAL 4 DAY),
DATE_SUB(CURDATE(), INTERVAL 5 DAY),
DATE_SUB(CURDATE(), INTERVAL 6 DAY),
DATE_SUB(CURDATE(), INTERVAL 7 DAY)
)
...
PS : FROM DUAL is superfluous in MySQL

mysql use a different set of WHERE statements if this=1

I need to do a single select on a table, but if Product='football' I need to do a couple of WHEREs, but if Product='something' then do something else. I am not sure if I need to do an IF statement, or a UNION or a CASE which I have never used.
Example of what I would like to have worked but obviously doesn't
SELECT *
FROM
orders
IF Product = 'Football'{
WHERE
AND RenewalDate < DATE_ADD(CURDATE(), INTERVAL 31 DAY)
AND RenewalDate > DATE_SUB(CURDATE(), INTERVAL 31 DAY)
}ELSE IF Product = 'Something'{
AND RenewalDate < DATE_ADD(CURDATE(), INTERVAL 10 DAY)
AND RenewalDate > DATE_SUB(CURDATE(), INTERVAL 10 DAY)
}
ORDER BY
RenewalDate
Now I know that looks like php but its just to show roughly what I want to happen
No if required. Just boolean logic:
SELECT o.*
FROM orders o
WHERE (Product = 'Football' AND
RenewalDate < DATE_ADD(CURDATE(), INTERVAL 31 DAY)
RenewalDate > DATE_SUB(CURDATE(), INTERVAL 31 DAY)
) OR
(Product = 'Something' AND
RenewalDate < DATE_ADD(CURDATE(), INTERVAL 10 DAY) AND
RenewalDate > DATE_SUB(CURDATE(), INTERVAL 10 DAY)
)
ORDER BY RenewalDate;

How do I retrieve data for the previous month in SQL

I want to get data for the dates between 2015-05-01 and 2015-06-01 using SQL.
Please help me with the query.
The query I used is:
select *,count(id) as multiple_visitors
from table1
where id=123
and (date(server_time) between (CURDATE() - INTERVAL 31 DAY) AND CURDATE())
group by user_id having count(id)>1
You can do this with month() and year():
where month(server_time) = month(curdate() - interval 1 month) and
year(server_time) = year(curdate() - interval 1 month)
However, I recommend a slightly more complex expression:
where server_time >= date_sub(date_sub(curdate(), interval - day(curdate()) + 1 day), interval 1 month) and
server_time < date_sub(curdate(), interval - day(curdate()) + 1 day)
The advantage is that there are no functions on server_time, so the database engine can use an index, if appropriate.
As a note: the expression date_sub(curdate(), interval - day(curdate()) + 1 day) gets midnight on the first day of the month.
Try using "WHERE" with MONTH(date).
Like this:
SELECT * FROM Table
WHERE MONTH(date) = 1

Query to get all rows from previous month

I need to select all rows in my database that were created last month.
For example, if the current month is January, then I want to return all rows that were created in December, if the month is February, then I want to return all rows that were created in January. I have a date_created column in my database that lists the date created in this format: 2007-06-05 14:50:17.
SELECT * FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
Here's another alternative. Assuming you have an indexed DATE or DATETIME type field, this should use the index as the formatted dates will be type converted before the index is used. You should then see a range query rather than an index query when viewed with EXPLAIN.
SELECT
*
FROM
table
WHERE
date_created >= DATE_FORMAT( CURRENT_DATE - INTERVAL 1 MONTH, '%Y/%m/01' )
AND
date_created < DATE_FORMAT( CURRENT_DATE, '%Y/%m/01' )
If there are no future dates ...
SELECT *
FROM table_name
WHERE date_created > (NOW() - INTERVAL 1 MONTH);
Tested.
Alternatively to hobodave's answer
SELECT * FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
You could achieve the same with EXTRACT, using YEAR_MONTH as unit, thus you wouldn't need the AND, like so:
SELECT * FROM table
WHERE EXTRACT(YEAR_MONTH FROM date_created) = EXTRACT(YEAR_MONTH FROM CURDATE() - INTERVAL
1 MONTH)
SELECT *
FROM yourtable
where DATE_FORMAT(date_created, '%Y-%m') = date_format(DATE_SUB(curdate(), INTERVAL 1 month),'%Y-%m')
This should return all the records from the previous calendar month, as opposed to the records for the last 30 or 31 days.
Even though the answer for this question has been selected already, however, I believe the simplest query will be
SELECT *
FROM table
WHERE
date_created BETWEEN (CURRENT_DATE() - INTERVAL 1 MONTH) AND CURRENT_DATE();
WHERE created_date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY)
AND created_date <= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH)), INTERVAL 0 DAY)
This worked for me (Selects all records created from last month, regardless of the day you run the query this month)
Alternative with single condition
SELECT * FROM table
WHERE YEAR(date_created) * 12 + MONTH(date_created)
= YEAR(CURRENT_DATE) * 12 + MONTH(CURRENT_DATE) - 1
select fields FROM table
WHERE date_created LIKE concat(LEFT(DATE_SUB(NOW(), interval 1 month),7),'%');
this one will be able to take advantage of an index if your date_created is indexed, because it doesn't apply any transformation function to the field value.
Here is the query to get the records of the last month:
SELECT *
FROM `tablename`
WHERE `datefiled`
BETWEEN DATE_SUB( DATE( NOW( ) ) , INTERVAL 1
MONTH )
AND
LAST_DAY( DATE_SUB( DATE( NOW( ) ) , INTERVAL 1
MONTH ) )
Regards
- saqib
if you want to get orders from last month, you can try using
WHERE MONTH(order_date) = MONTH(CURRENT_DATE()) -1
One more way to do this in:
MYSQL
select * from <table_name> where date_created >= DATE_ADD(NOW(), INTERVAL -30 DAY);
SELECT * FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)