SQL view syntax - mysql

so I have a table I want to create a view with, but not entirely sure how to go about it..
So lets say we have a table with:
Index
Country
City
Population
and I want to make a view showing each country and the sum of it's population, it sounds easy, but I am having trouble wrapping my head around the SELECT used to create the view.
Just standard mySQL if it makes any difference. Thanks!

For MySQL could be something like:
SELECT country, SUM(population) as total_population
FROM table
GROUP BY country

To create a view in MYSQL:
CREATE VIEW v_country_population
AS
SELECT country, SUM(population) as total_population
FROM cities
GROUP BY country

Related

Filtering Queries, Adding a field to a query that isn't in the table

I need help with sorting and adding a field to a query that hasn't been made yet.
For the first bullet, I'm confused at the last part where it asks you to sort by one field, and then within that field, sort again. "Sort the records in ascending order by Region, and within Region, by Product Name." How would I sort it only for Region? or am I not understanding the question...
And for the second bullet, how would I create the field "Extended Price" in a query when it hasn't been created in the table? I'm sure I could handle the rest of that but all I need to know is if there is a way to create a field through query without it being created in the table its based on...
Thank you. (BTW this is a practice question. This practice assignment in no way, shape, or form will benefit my grade)
Use the query builder to construct SQL. The result should be something like:
SELECT ProductID, ProductName, Category, UnitsInStock, UnitPrice, SupplierID, SupplierName, Region, UnitsInStock * UnitPrice AS ExtendedPrice FROM Products INNER JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID ORDER BY Region, ProductName;
select p.product_name,p.category,p.supplier_id,s.supplier_name,s.region,s.unitprice
from products p join supplier s
on p.supplier_id=s.supplier_id
BTW this may work , if you modify accordingly

Get data from table by County in a single row

I want to get data from table in a single row for single county. Right now as shown in images it shows Different rows for Single county as Kalamazoo. It should show single with both records in single row.
I am using following query
SELECT County, Virus, SumOfPositiveTests
FROM StatewiseData
WHERE State = 'MICHIGAN'
I want the results to be shown as following
County Virus SUMOFPOSITIVETESTS
---------------------------------------------
Kalamazoo H3N2,H3N8 3
Total sum of both H3N2 and H3N8
use MYSQL GROUP_CONCAT
The following MySQL statement will return a list of comma(,) separated 'Virus's for each group of 'County' from the StatewiseData table
SELECT County,GROUP_CONCAT(Virus),sum(SumOfPositiveTests) FROM StatewiseData where State='MICHIGAN' group by County
Try this if you are using mysql:
SELECT country, GROUP_CONCAT(virus) _virus, SUM(SumofPositiveTests) as TotalPostitiveTest
FROM StatewiseData
WHERE Country = 'Kalamzoo'
GROUP BY Country
Please mind that this will not work with most databases, as they need you to to specify only the grouping field and aggregate functions of other fields in your query.
Here is the source
Try this. this would work on IBM DB2 and MySQL. what DB you are using
SELECT DISTINCT Country, Virus,SumOfPositiveTests FROM Customers where State='MICHIGAN' group by Country;
why are you using state in where condition? (please provide list of columns do you have in a column if i missed something)
if you are only selecting the country then it should be as simple as:
SELECT County,Virus,SumOfPositiveTests FROM StatewiseData where Country='Kalamzoo'
if you want to select summary or totals of single country then you you should use sum like:
SELECT country, SUM(SumofPositiveTests) as TotalPostitiveTest
FROM StatewiseData WHERE Country='Kalamzoo' GROUP BY Country

In SQL how do you output a column that is performing a function on multiple columns?

I'm learning SQL (specifically mySQL) and I've been working through the problem sets on sqlzoo.
I've gotten stumped by one problem that is asking me to show the population of a country as a percentage of some other country. It's number 5. Please note the full table is not shown, but the content of the table can be inferred given the parameters: world(name, continent, area, population, gdp)
I am not sure of two things:
how to perform the division function between the data in two columns, and
how to convert this data into a percentage without creating a new variable (using 'AS').
Here is what I have tried (indented for readability):
SELECT name, CONCAT(ROUND(new_population))from world WHERE
continent = 'Europe' AND
((SELECT population AS new_population from world) /
(SELECT population FROM world where name='Germany'));
The error given is "Unknown column 'new_population' in 'field list'" which leads me to believe I don't understand how 'AS' works.
I realize that this doesn't really make sense because the values that come after 'AND' are new ones, and so they can't be conditions on my original select statement. But I'm not really sure how to incorporate the function otherwise.
Also, please be patient, as I am teaching this to myself, so I don't really have anyone to guide me through it. Thank you!
You are on the right track, but you want to do this logic up in your SELECT instead of down in the WHERE. WHERE is for filtering your result set only. SELECT is where you put the things you want in your result set.
SELECT
name,
population/(SELECT population FROM world WHERE name='Germany' limit 1) * 100
FROM world
WHERE continent = 'Europe'
Alternatively you could do this with a CROSS JOIN:
SELECT
name,
world.population/germany.population * 100
FROM world CROSS JOIN (SELECT population FROM world WHERE name = 'Germany') as germany
WHERE continent = 'Europe'
Not too sure which one is more kosher with the tutorial you are following.
I just want to add a little detail on #JNevill answer
Here is the query:
SELECT name, CONCAT(ROUND(population/(SELECT population FROM world WHERE name = 'Germany')*100), '%') AS population
FROM world
WHERE continent = 'Europe'
You use here CONCAT to connect your result with % sign so you get 11%, 0%, 5%etc.. ROUND function is used to make whole number from result... In calculation you will get something like 11.15478 and they want to show result as 11%.. That's way they want to use CONCAT AND ROUND here..
GL!

Problems with CREATE VIEW

The question is to create a view called NumberOfCities_v. And then use the view to list
countries that have more than 20 cities in the descending order of number of cities.
This is my create a view statement:
CREATE VIEW NumberOfCities_v AS
SELECT
country.code as "Country Code",
country.name as Country,
count(countrycode) as "Number Of Cities"
FROM
city,
country
WHERE
city.countrycode = country.code
GROUP BY country.code, country.name
HAVING COUNT(countrycode) > 20
ORDER BY COUNT(countrycode) desc;
I don't get any records, but I think I've created the view. According to my powerpoint, I should be getting both. Apparently I have some field errors with that statement with I try to select the view with another statement. But When I use the exact statement without the create view, I get the results I need. Can someone explain why that is?
You need to fire sql query:
Select * from `NumberOfCities_v`
to get all the records generated in view.

How to display the first and second Doctor to see a patient?

I have to create a table where there are lots of columns pulling date from one table and two views. To display the columns is no problem. The problem comes into play when I have to alias two columns to show a patient who received services from the first two distinct doctors (doctor_1 and doctor_2). Each doctor has their own ID. I’m not sure if I should use the “distinct top (2)”, “rank”, etc… Here is what it sort of looks like.
Date, LastName, FirstName, Address, City, State, Zip, Hostital, Room, Doctor_1,Doctor_2
Any help would be greatly appreciated.
Let's assume your table looks something as follows:
doctor_patients:
doctor_id int,
patient_id int,
visit_date datetime
In that case you can write a query similar to the following:
select a.patient_id, b.doctor_id as doctor_1, b.visit_time_max as doctor_1_visit_time, a.doctor_id as doctor_2, max(a.visit_time) as doctor_2_visit_time
from doctor_patients a
inner join
(select patient_id, doctor_id, max(visit_time) as visit_time_max
from doctor_patients
where visit_time < a.visit_time
and patient_id = a.patient_id
and doctor_id = a.doctor_id) b
You can always put a where clause at the tail end and apply filters to the "a" table. I am not sure if this query will run as-is because I did not try it out on SQL. But I hope this gives you a general idea about what you need to do. There might be better ways to accomplish this using latest SQL features but this should get you rolling. I hope this is the answer you were looking for!