I am quite new to mySQL and need help.
I have a database like this (values are example):
name |region |population|
----------------------------------
Cuba |Carribean |10 |
Ukraine|Eastern Europe|15 |
Belarus|Eastern Europe|9 |
Haiti |Carribean |3 |
I want to find total population of the region (e.g. all population from Eastern Europe) and print as a table the region name and its total population.
But I have no idea how to find a sum of field value from one column but under condition from another column.
How to to do this query?
SELECT region, SUM(population) AS population
FROM table
GROUP BY region
Try below query:
select name , region , sum(population)
from region_table // table_name
group by name , region
May be this will help you.
Related
I need to print every city from table which has at least one student in every generation. Table is simple but I don't know how to extract every year from that table, because its string.
indeks | city
1/2018 | London ;
2/2018 | Paris ;
3/2018 | null;
4/2019 | London ;
4/2020 | London;
In this case SQL query needs print London, because every year from table has one student (2018,2019 and 2020). I have no idea how to even start query :}
I'd try something like that:
select city from
(
select
city, count(distinct cast(SUBSTRING(indeks, LOCATE('/', indeks)+1) as unsigned)) as dy
from cities
group by city
) as t
where
dy = (
select
max(cast(SUBSTRING(indeks, LOCATE('/', indeks)+1) as unsigned))-min(cast(SUBSTRING(indeks, LOCATE('/', indeks)+1) as unsigned))+1
from cities
)
so in inner query it will calculate how many different years are filled for the each city
outer filter will check which one has all of them
So there is a question I have not been able to find an answer to. Say you want to print each row in a table like the following:
ID | Name | Location
----+------+----------
1 | Adam | New York
2 | Eva | London
3 | Jon | New York
which would give the result
1 Adam New York
2 Eva London
3 Jon New York
Say that I at the same time would like to count the number of occurrences someone lives in a specific city, and save that value for printing after I've iterated through the table; is that possible? For example, printing the following:
1 Adam New York
2 Eva London
3 Jon New York
Inhabitants in New York: 2
Inhabitants in London: 1
Is this possible or would you have to iterate through the entire table twice by grouping by Location the second time, and counting those?
EDIT:
To clarify, I know I can solve it by calling:
SELECT * FROM table;
SELECT CONCAT('Inhabitants in ', Location, ': ', COUNT(ID))
FROM table
GROUP BY Location;
But now I am iterating through it twice. Is it possible to do it in only one iteration?
Generally speaking, yes, displaying every row from the table and displaying aggregated data is two separate tasks which should be handled by application, not by the database.
You have the option to run two queries - a plain select * from T, and select location, count(*) from T group by location, and displaying results sequentially. You also have the option to run only a select * from T one, and count the rows within your application, since you're displaying all rows anyway: use any dictionary-like structure your app language provides, with location string for key and running total integer for value.
If you're keen on keeping it a single query, check out WITH ROLLUP clause - https://dev.mysql.com/doc/refman/8.0/en/group-by-modifiers.html. This would certainly be an unusual way of using it, but if you group by location, id and then tamper with results a little, you can get what you want.
select if(id is null, CONCAT('Inhabitants in ', location, ': ', cnt), concat(id, ' ', name, ' ', location))
from
(
select id, location, name, count(*) cnt
from t
where location is not null
group by location, id with rollup
) q
where location is not null
order by id is null, id asc;
Though the performance could be questionable, compared to two plain queries; you should experiment or check with EXPLAIN.
Try below query, use subquery
select concat(concat(concat('Inhabitants in ',location),':'),total)
from
(select location, count(id) total
from tablename group by location)a
table 1: employee
name| mobile| location
alex| 123 | australia
john| 456 | paris
kohl| 678 | australia
table 2:employment
id|location |data
1 |australia|[{"name":"alex","mobile":"123"},{"name":"kohl","mobile":"678"}]
2 |paris |[{"name":"john","mobile":"456"}]
i have two tables named "employee" and "employment". How can i get all the column values of employee table into one column of employment table as shown in table 2. I am new to SQL querying. I honestly don't have any idea on how to proceed. Any pointers and suggestions are appreciated.
You can use the following solution using CONCAT and GROUP_CONCAT to get this result:
SELECT location, CONCAT("[", GROUP_CONCAT(CONCAT('{"name":"', name, '","mobile":"', mobile, '"}')), "]") AS data
FROM employee
GROUP BY location
demo: http://sqlfiddle.com/#!9/ab25ee/2/0
To JOIN the employee table with the employment you can use the following solution:
SELECT employment.id, employment.location, CONCAT("[", GROUP_CONCAT(CONCAT('{"name":"', name, '","mobile":"', mobile, '"}')), "]") AS data
FROM employment INNER JOIN employee ON employment.location = employee.location
GROUP BY id, location
demo: http://sqlfiddle.com/#!9/12f9c9/1/0
My database is missing some values:
Name Surname Country Salary
John Walker USA 800
Walker Canada 1000
Peter Walker Canada 800
John Walker 900
Peter Farmer USA 1200
... ... ...
I want to SELECT Name and Surname and Country, if there are no values,
I want to SELECT by Name and Country, if there are no values,
I want to SELECT by Surname and Country.
I am using now:
SELECT Salary FROM table_name
WHERE (Name='InputFromPHP' AND Surname='InputFromPHP' AND Country='InputFromPHP')
OR (Name='InputFromPHP' AND Surname='InputFromPHP')
OR (Name='InputFromPHP' AND Country='InputFromPHP')
I want to give priority, so it will select exactly what was Input With PHP, but when there are several values in database it gives SQL error.
Thanks a million in advance.
You could use order by and limit:
SELECT Salary
FROM table_name
WHERE Name='InputFromPHP'
AND (Surname='InputFromPHP' OR Country='InputFromPHP')
ORDER BY CASE Surname WHEN 'InputFromPHP' THEN 0 ELSE 1 END,
CASE Country WHEN 'InputFromPHP' THEN 0 ELSE 1 END
LIMIT 1
Note that your where clause always required Name='InputFromPHP', so that can be taken out of the or clause.
To make it more clear, If I have this data in MySql:
name | allowance | age
----------------------
khan | 50 | 20
aal | 60 | 22
hyme | 50 | 21
khan | 61 | 20
notice that there are two 'khan' in the database with different allowance. I want to only show the name and the age but if I show it using the mysqli select statement, there would be two 'khan' but I only want to show only 1 'khan'. How can I do it?
You need to use GROUP_CONCAT to see agges of all Khans;
select name, GROUP_CONCAT(age) ages from Table group by name
or for minimum aged khan
select name , min(age) MiniumAge from Table group by name
or for elder khan
select name , max(age) MaxAge from Table group by name
or any khan
select name , age from Table group by name
.
Please try below query:-
SELECT name, age FROM table_name WHERE group by name
If you want any from multiple same record then simply used group by query.
I think you could do this:
SELECT name, age FROM table_name WHERE group by name,age
First thing: if both those "khan"s are the same person with two different allowances then your schema is not properly normalized and it will give you big troubles later - imagine you want to change "khan" to "Khan" - now you have to update it in multiple places instead once. Depending on your actual needs you may want one table of people (person_id, name, age), and table of allowances (person_id, allowance, [..some other parameters?..]).
Second, to really get what you want, either you use group by, to get one "random" row per each name as suggested in other answers, or you can do
SELECT DISTINCT name, age FROM table;
which will give you one row per each name-age combination, so khan-20 will be there only once - but if there were khan-25 then that is probably different person and you would have two khans returned, each with their own age.
You can try this mate:
SELECT DISTINCT
name, age
FROM
<your_table>;
or this one
SELECT
name, age
FROM
<your_table>
GROUP BY
name;
Q: Is there any chance that if there are 2 records of tha same name have difference value of age? If so, kindly update the question so that better answers will be given. Cheers!