I have table named table_food in db with columns: first name, last name, date, food name. I want a query that returns all food names from specified date.
For example my table records looks like:
John Watson 2016-08-22 steak
John Watson 2016-08-22 burger
John Watson 2016-08-23 fries
John Watson 2016-08-23 apple
and I want to get all food names from 2016-08-23. How should I create my query?
I´m just assuming you´re using a MySQL-Database. The answer may vary for other databases.
There are two versions, depending on what you´re trying to get.
If you just want a list of all foods, including duplicates, you could use:
select food_name from table_food where date = '2016-08-23'
If you just need to get distinct values (each food name once) you could use:
select distinct(food_name) from table_food where date = '2016-08-23'
The first question could be: Which meals have been served and how many of them?
The second question could be: Which meals have been served at all (no matter how often)
It depends from the database you use.
I added also a distinct because I imagine that you need only distinct values of food names.
For MySql
select distinct(food_name) from table_food
where date = '2016-08-23'
For Oracle
select distinct(food_name) from table_food
where date = to_date('2016-08-23', 'YYYY-MM-DD')
Check for dialects of other databases.
Note that if the data stored in the date column has also hours, minutes and seconds you need a different query to extract data, for example in oracle:
select distinct(food_name) from table_food
where trunc(date) = to_date('2016-08-23', 'YYYY-MM-DD')
$date = "2016-08-23";
SELECT * FROM `table_food` WHERE `date` = '{$date}';
The reason I'd variable the date is solely down to as and when you wish to change the date. Don't get me wrong either of the above you can do. My personal preference would be to adjust the variable rather than the query.
When you need to retrieve data from a table, you'll have to specify what field you need to select from what table, under one or several conditions.
Since your condition is the date,
we'll use this syntax:
We added the word distinct in case you didn't need redundancy.
Select distinct FoodName
from Table_Food
Where date = '2016-08-23'
Related
I am practicing writing SQL queries, I'm working with a baseball database. The table I'm concerned with is named people with attributes nameFist, nameLast, debute_date, and final_game.
I'm attempting to find the first name and last name (as one field) and debut date of people whose final game was 10,000 days after their debut. Order by the date difference.
So far I have:
SELECT CONCAT(nameFirst,'',nameLast) as name, debut_date FROM
PEOPLE;
How would I find the people whose final game was 10,000 days after their debut? debute_date and final_game are formatted like so: Year-Month-Day e.i. 2014-02-28.
I can't just simply add 10,000 days to final_game.
You can try using the DATEDIFF function. So the query would look something like this:
SELECT CONCAT(nameFirst,' ',nameLast) as name, debut_date
FROM PEOPLE
WHERE DATEDIFF(final_game, debut_date) > 10000
ORDER BY DATEDIFF(final_game, debut_date);
The DATEDIFF function may vary depending on if you are using MySQL or SQL SERVER.
For SQL SERVER, the query might look like this:
SELECT CONCAT(nameFirst,' ',nameLast) as name, debut_date
FROM PEOPLE
WHERE DATEDIFF(d, debut_date, final_game) > 10000
ORDER BY DATEDIFF(d, debut_date, final_game);
edited as requested:
My apologies. I've been dealing with this a bit and it's well and truly in my head, but not for the reader.
We have multiple records in table A which have multiple entries in the Period column. Say it's like a football schedule. Teams will have multiple dates/times in the Period column.
When we run query:
We want records selected for the most recent games only.
We don't want the earlier games.
We don't want the games "scheduled" and not yet played.
"Last game played" i.e. Period for teams are often on different days.
Table like:
Team Period
Reds 2021020508:00
Reds 2021011107:00
City 2021030507:00
Reds 2021032607:00
City 2021041607:00
Reds 2021050707:00
When I run query, I want to see the records for last game played regardless of date. So if I run the query on 27 Mar 2021, I want:
City 2021030507:00
Reds 2021032607:00
Keep in mind I used the above as an easily understandable example. In my case I have 1000s of "Teams" each of which may have 100+ different date entries in the Period column and I would like the solution to be applicable regardless of number of records, dates, or when the query is run.
What can I do?
Thanks!
So this gives you your desired output using the sample data, does it fulfil your requirement?
create table x (Team varchar(10), period varchar(20))
insert into x values
('Reds','2021020508:00'),
('Reds','2021011107:00'),
('City','2021030507:00'),
('Reds','2021032607:00'),
('City','2021041607:00'),
('Reds','2021050707:00')
select Team, Max(period) LastPeriod
from x
where period <=Format(GetDate(), 'yyyyMMddhh:mm')
group by Team
The string-formatted date you have order by text, so I think this would work
SELECT TOP 2 *
FROM tableA
WHERE period = FORMAT( GETDATE(), 'yyyyMMddhh:mm' )
ORDER BY period
Perhaps you want:
where period = (select max(t2.period) from t t2)
This returns all rows with the last period in the table.
I am pretty new to SQL, but i need to use it for my new job as the project requires it and as I am a non-IT-guy, it is more difficult for me, because thats my first time I work professionally with SQL.
Hopefully you can help me with it: (Sry for my english, i am a non-native speaker)
I need to start a query where I get unequal IDs from 2 different reference dates.
So I have one Table with following data:
DATES ID AMOUNT SID
201910 122424 99999 1
201911 41241242 99999 2
201912 12412424 -22222 3
...
GOAL:
So the ID's from the DATE: 201911 shall be compared with those from 201910
and the query should show me the unequal ID's. So only the unmatched ID's shall be displayed.
Out of this query, the Amount should be summed up and grouped into SIDs.
If you have two dates and you want sids that are only on one of them, then:
select sid
from t
where date in (201911, 201910)
group by sid
having count(distinct date) = 1;
My question is how to properly write a SQL query for the below highlighted/bold question.
There is a table in HMO database which stores doctor's working
hours.Table has following fields
"FirstName","LastName","Date","HoursWorked". write a sql statement
which retrieves average working hours for period January-March for a
doctor with name Joe Doe.
so far i have
SELECT HoursWorked
FROM Table
WHERE DATE = (January - March) AND
SELECT AVG(HoursWorked) FROM Table WHERE FirstName="Joe",LastName="Doe"*
A few pointers as this sounds like a homework question (which we don't answer for you here, but we can try to give you some guidance).
You want to put all the things you want to return from your select first and you want to have all your search conditions at the end.
So the general format would be :
SELECT Column1,
Column2,
Column3,
FROM YourTable
WHERE Column4 = Restriction1
AND Column5 = Restriction2
The next thing you need to think about is how the dates are formatted in your database table. Hopefully they're kept in a column of type datetime or date (options will depend on the database engine you're using, eg, Microsoft SQL Server, Oracle or MySql). In reality some older databases people use can store dates in all sorts of formats which makes this much harder, but since I'm assuming it's a homework type question, lets assume it's a datetime format.
You specify restrictions by comparing columns to a value, so if you wanted all rows where the date was after midnight on the 2nd of March 2012, you would have the WHERE clause :
WHERE MyDateColumn >= '2012-03-02 00:00:00'
Note that to avoid confusion, we usually try to format dates as "Year-Month-Day Hour:Minute:Second". This is because in different countries, dates are often written in different formats and this is considered a Universal format which is understood (by computers at least) everywhere.
So you would want to combine a couple of these comparisons in your WHERE, one for dates AFTER a certain date in time AND one for dates before another point in time.
If you give this a go and see where you get to, update your question with your progress and someone will be able to help get it finished if you have problems.
If you don't have access to an actual database and need to experiment with syntax, try this site : http://sqlfiddle.com/
you already have the answer written
SELECT AVG(HoursWorked) FROM Table WHERE FirstName="Joe",LastName="Doe"*
you only need to fix the query
SELECT AVG(HoursWorked) as AVGWORKED FROM Table WHERE FirstName='Joe' AND LastName='Doe'
That query will give you the average hours worked for Joe Doe, however you only need to get between some time you add the next "AND", if you are using SQL server you can use the built in function DateFromParts(year,month,day) to create a new Date, or if you are using another Database Engine you can convert a string to a DateColumn Convert(Date,'MM/dd/yyyy')
Example
SELECT AVG(HoursWorked) as AVGWORKED FROM Table WHERE FirstName='Joe' AND LastName='Doe' AND DateColumn between DateFromParts(year,month,day) and Convert(Date,'MM/dd/yyyy')
In the example i showed both approaches (datefromparts for the initial date, and convert(date) for the ending date).
How does Min function work on dates ? If 2 records have the same date and time stamp , the min function returns 1. Does it pull records based on when it was put into the table ?
MIN is an aggregate function so it will return 1 record in your question's case. Since the two records have the same date and timestamp it doesn't matter which date and timestamp are returned (they're the same). Finally, the time the records were inserted is not considered.
MIN() returns the smallest of all selected values of a column. It seems to me that your statement may simply be asking if a minimum exists.
Please post your sql statement.
possibly this is what you need:
SELECT MIN (date) AS "Min Date"
FROM tablename;
Elliot already expained it.
Just a sidenode, if you are using MySQL: MySQL allows to aggregate on a certain column, while fetching other columns without aggregation. (SQL Server does NOT allow that!)
Example:
date | name
2015-03-06 | A
2015-03-06 | B
Using SELECT Min(date), name FROM table on MySQL will return various results.
Sometimes it will be
2015-03-06 | A
sometimes
2015-03-06 | B
Docu:
When using this feature, all rows in each group should have the same
values for the columns that are omitted from the GROUP BY part. The
server is free to return any value from the group, so the results are
indeterminate unless all values are the same.
SQL Server will throw an error, that no aggregation has been performed on column name. See also http://dev.mysql.com/doc/refman/5.0/en/group-by-handling.html
MySQL works this way, cause sometimes grouping on the second column is not really required, for example:
SELECT MAX(id), user_id FROM posts WHERE user_id = 6
(There could be NO other user_id than 6, so aggregation is not required in MySQL - However not paying attention on THIS will lead to wrong results as example one shows.)