How to search SQL records by date of birth? - mysql

I have a SQL-table where I have records of my clients such as first name, last name, date of birth etc.
Now I try to find all clients by date of birth (for cron, sending holiday and birthday greetings).
Therefore, I need to find all existing clients with a specific date of birth.
For example:
In the SQL table I have a few records with these birth dates.
+==================+
| Date_of_birthday |
====================
| 1981-06-30 |
--------------------
| 1972-06-30 |
--------------------
| 1966-10-07 |
====================
Now I need to return all clients who were born on June 30th.
I tried:
SELECT * FROM `table`
WHERE DATE(Date_of_birthday) = '####-06-30';
But my pattern does not seem to work properly, it doesn't return any lines.
The hashtag character '#' should represent any numeric character, but it doesn't work.
Where is my mistake? Or do I have to write the SQL query differently?

With DATE_FORMAT():
SELECT * FROM `table`
WHERE DATE_FORMAT(Date_of_birthday,'%m-%d') = '06-30';

This query should do:
select *
from YourTable
where datepart(day, date_birth) = 30
and datepart(month, date_birth) = 06

SELECT * FROM `table`
WHERE right(Date_of_birthday, 5) = '06-30'

Related

How can I separate a single column into 3 separate columns

Want to execute a query to view single date-month-year time column to separate date column, month column and year column.
eg
joining_date
01-JAN-22 12.00.00AM
to
joining_date|joining_month|joining_year
01 | JAN | 22
You have some ways of doing this:
If your data is always in this 01-JAN-22 12.00.00AM format , no matter what comes after 22, you can use substring.
select substring('01-JAN-22 12.00.00AM',1,2) as joining_date,
substring('01-JAN-22 12.00.00AM',4,3) as joining_month,
substring('01-JAN-22 12.00.00AM',8,2) as joining_year;
Result:
joining_date joining_month joining_year
01 JAN 22
Another option is converting the string to proper date datatype an use MySQL functions, like :
select DAY(str_to_date('01-JAN-22 12.00.00AM', "%d-%b-%y")) as joining_date,
MONTH(str_to_date('01-JAN-22 12.00.00AM', "%d-%b-%y")) as joining_month,
YEAR(str_to_date('01-JAN-22 12.00.00AM', "%d-%b-%y")) as joining_year ;
Result:
joining_date joining_month joining_year
1 1 2022
Fiddle
Use YEAR, MONTH and DAY syntax:
SELECT
YEAR(`joining_date`) as joiningYear,
MONTH(`joining_date`) as joiningMonth,
DAY(`joining_date`) as joiningDay
FROM tableName
If you want your month name, then use MONTHNAME:
SELECT
YEAR(`joining_date`) as joiningYear,
MONTHNAME(`joining_date`) as joiningMonth,
DAY(`joining_date`) as joiningDay
FROM tableName

SQL Query Select Clause, need a solution to not return few rows

I have a column in a static table like this:
Vehicles
-------------
Bike
Truck
car_2018
car_2019
car_2020
car_2021
Bus
The select query needs to fetch only the car row based on the year of query (for example now its 2018, if I run this next year, it should get back _2019) long with the rest of the rows that's not based on years. Need a solution for this.
So far I have this:
SELECT Vehicles
FROM VehicleMaster
WHERE 'some where clause based on other columns'
select Vehicles
from table_name
where Vehicles like '%2018'
union all
select Vehicles
from table_name
where Vehicles not like '%car%'
You can use substring_index to split that field by underscore _ and query based on that:
CREATE TABLE vehicles(f1 varchar(30));
INSERT INTO vehicles VALUES ('Bike'),
('Truck'),
('car_2018'),
('car_2019'),
('car_2020'),
('car_2021'),
('Bus');
SELECT f1
FROM vehicles
WHERE
f1 NOT LIKE 'car%'
OR (f1 LIKE 'car%' AND substring_index(f1, "_", -1) = YEAR(CURDATE()));
+----------+
| f1 |
+----------+
| Bike |
| Truck |
| car_2018 |
| Bus |
+----------+
SqlFiddle here
You can use regex to exclude all car_#### rows, except for the current year. Assuming that your Vehicles column is called name, this should work for you:
select *
from Vehicles
where
(
-- Exclude all car_####
not trim(name) REGEXP '^car_[0-9]{4}$'
-- Except for the current year
or name = concat('car_', year(now()))
)
I think you want:
select t.*
from t
where t.vehicle = concat('car_', year(curdate())) or
t.vehicle not regexp '[0-9]{4}$'
If you want a general purpose "any current year or any without a year", then:
select t.*
from t
where t.vehicle like concat('%_', year(curdate())) or
t.vehicle not regexp '[0-9]{4}$'

Calculate percentage in mysql from the same column

How do i calculate the percentage from the same column, between two dates?
I have column latest.
For example: 2015-11-16 the value was 159,4 and today the value is 160,1.
And between these dates there is other values, that i´m not interested in at the moment. How to i calculate the percentage difference from that specific date, compared to "todays" date.
EDIT
SELECT curr.latest * 100 / NULLIF(prev.latest, 0) as percentage
FROM myTable AS curr, myTable AS prev
WHERE date(prev.timestamp) = '2015-11-16'
AND date(curr.timestamp) = CURDATE()
AND curr.the_row_namn = 'apple'
Percentage of column latest of a specific date ex. 2015-11-16, with the the_row_namn of apple from the table myTable.
What is the percentage difference of column latest for apple of the day 2015-11-16 to today.
+--------------+--------+------------+
| the_row_namn | latest | timestamp |
+--------------+--------+------------+
| apple | 159,40 | 2015-11-16 |
| apple | 164,1 | 2015-11-17 |
+--------------+--------+------------+
Expected output: (rounded) percentage: 0,2864 or even better if that is possible 2,8%
Hope this will clarify things.
You could do this with the following SELECT statement:
SELECT curr.name,
curr.value * 100 / NULLIF(prev.value, 0) as percentage
FROM myTable AS curr
INNER JOIN myTable AS prev
ON curr.name = prev.name
WHERE prev.latest = '2015-10-26'
AND curr.latest = CURDATE()
AND curr.name = 'apple';
If you leave out the last condition, you'll get a result per possible value of name.
The main point of this query is that you use your table twice, once to select the current record, and once to retrieve the earlier record. You should just specify the date of your choice in the first line of the where clause.
Once you have both records, it is straightforward to calculate a percentage from the value columns of these two records.
The NULLIF is there to protect you from division by zero errors. Instead you'll get a NULL result.
This is the general form such a query can take:
SELECT a.value / b.value AS abPerc
FROM the_table AS a
INNER JOIN the_table AS b ON [pairing criteria]
;

SQL - How can I get the quantity of parts from this query and still have all the notes associated with these requests?

Select p.Description
, cast(floor(cast(f.CreatedDate as float)) as datetime) as RequestDate
, Sum(f.Quantity) as QuantityOfParts
, Coalesce(n.Note + ' / ','') as Notes
from FulfillmentLine f
join Part p
on p.PartGUID = f.PartGUID
left
join Note n
on n.ParentGUID = f.FulfillmentLineGUID
where cast(floor(cast(f.CreatedDate as float)) as datetime) between '2015-02-01' and '2015-02-19'
Group
by p.Description
, cast(floor(cast(f.CreatedDate as float)) as datetime)
, Coalesce(n.Note + ' / ','')
order
by cast(floor(cast(f.CreatedDate as float)) as datetime)
In this query I am checking our database for all fufillment requests in a certain date range based on part requested and date requested. The not table is linked to the request in its own table and has any important notes about the request. An example would be if the item is not in our database but still can be ordered. What I want is that even if a part is requested multiple times in one day I want that total quantity in one row. The problem is that if there is more than one note then a row is created for each note. Is there a way to change my query so that all the notes for the parts are listed in one row.
Example:
What I have now:
See Note | 2015-02-01 | 5 | Pads of paper/
See Note | 2015-02-01 | 7 | Syringes/
See Note | 2015-02-01 | 2 | Packs of pens/
What I want:
See Note | 2015-02-01 | 14 | Pads of paper/ Syringes/ Packs of Pens
Try something like:
SELECT name, date, count(column), GROUP_CONCAT(`field` separator ',') as `myfield`
FROM mytable
GROUP BY name, date
If you are using SQL server, the Stuff function would work for you.
Here is an example for you to review

Given a date find the previous &/or current and next x# Dates in MySQL non-linear

I have a table code_prices that looks something like this:
CODE | DATE | PRICE
ABC | 25-7-2011 | 2.81
ABC | 23-7-2011 | 2.52
ABC | 22-7-2011 | 2.53
ABC | 21-7-2011 | 2.54
ABC | 20-7-2011 | 2.58
ABC | 17-7-2011 | 2.42
ABC | 16-7-2011 | 2.38
The problem with the data set is there are gaps in the dates, so I may want to look for the price of item ABC on the 18th however there is no entry because the item wasnt sold on this date. So I would like to return the most recent hisotrical entry for the price.
Say if I query on the date 19-7-2011, I would like to return the entry on the 17th then the next 10 avalaible entries.
If however I query for the price of ABC on the 20th, I would want to return the price on the 20th and the next 10 prices after that...
What is the most efficient way to go about this either in SQL statement or using a stored proc.
I can think of just writing a stored proc which takes the date as a param and then querying for all rows where DATE >= QUERY-DATE ordering by the date and then selecting the 11 items (via limit). Then basically I need to see if that set contains the current date, if it does then return, otherwise I will need to return the 10 most recent entires out of those 11 and also do another query on the table to return the previous entry by getting the max date where date < QUERY-DATE. I am thinking there might be a better way, however I'm not an expert with SQL (clearly)...
Thanks!
This is for one specific code:
SELECT code, `date`, price
FROM code_prices
WHERE code = #inputCode
AND `date` >=
( SELECT MAX(`date`)
FROM code_prices
WHERE code = #inputCode
AND `date` <= #inputDate
)
ORDER BY `date`
LIMIT 11
For ABC and 19-7-2011, the above will you give the row for 17-7-2011 and the 10 subsequent rows (20-7-2011, 21-7-2011, etc)
I'm not entirely clear on what you want to achieve, but I'll have a go anyway. This searches for the ID of the row that contains a date less than or equal to your specified date. It then uses that ID to return all rows with an ID greater than or equal to that value. It assumes that you have a column other than the date column on which the rows can be ordered. This is because you said that the dates are non-linear - I assume that you must have some other way of ordering the rows.
SELECT id, code, dt, price
FROM code_prices
WHERE id >= (
SELECT id
FROM code_prices
WHERE dt <= '2011-07-24'
ORDER BY dt DESC
LIMIT 1 )
ORDER BY id
LIMIT 11;
Alternative with code condition - thanks to #ypercube for highlighting that ;-)
SELECT id, code, dt, price
FROM code_prices
WHERE code = 'ABC'
AND id >= (
SELECT id
FROM code_prices
WHERE dt <= '2011-07-23'
AND code = 'ABC'
ORDER BY dt DESC
LIMIT 1 )
ORDER BY id
LIMIT 11;