Count number of users from a certain country - sql

I have a table of users, and in this table I have a country field telling where these people are from (i.e. "Sweden", "Italy", ...). How can I do a SQL query to get something like:
Country Number
Sweden 10
Italy 50
... ...
Users select their countries from a list I give to them, but the list is really huge so it would be great to have a SQL query that can avoid using that list, that is look in the DB and give back only those countries which are in the database, because for example I have nobody from Barbados, even if I have that option in the country select field of the signup form :)
Thanks in advance!

If the name of the country is in the Users table, try something like this:
SELECT Country, COUNT (*) AS Number
FROM Users
GROUP BY Country
ORDER BY Country
If the name of the country is in the country table, then you will have to join
SELECT Contries.CountryName, Count (*) AS Number
FROM Users
INNER JOIN Countries
ON Users.CountryId = Countries.CountryId
GROUP BY Countries.CountryName
ORDER BY Countries.CountryName

This will give what you want. But you might want to cache the result of the query. With a lot of users it's quite a heavy query.
SELECT
country,
COUNT(*)
FROM
users
GROUP BY
country
Perhaps a better idea is (assuming you don't need the counts) to do it like this:
SELECT
DISTINCT country
FROM
users

Sounds like you want something like this...?
SELECT Country, COUNT(*) AS Number
FROM Users
GROUP BY Country

This is pretty straightforward:
SELECT
Country, COUNT(*) AS 'Number'
FROM
YourTable
GROUP BY
Country
ORDER BY
Country
You just group your data by country and count the entries for each country.
Or if you want them sorted by the number of visitors, use a different ORDER BY clause:
SELECT
Country, COUNT(*) AS 'Number'
FROM
YourTable
GROUP BY
Country
ORDER BY
COUNT(*) DESC

If you want the count per country:
select country, count(*) from users group by country;
If you just want the possible values:
select distinct country from users;

SELECT BillingCountry, COUNT(*)as Invoices
FROM Invoice
GROUP BY BillingCountry
ORDER BY Invoices DESC

Related

SQL query to count number of rows with same value

I have this table data:
I want to perform an sql query which will give me the total number of distinct loan applications per city.
So for example, I would expect this output
City Wexford
Loans 1
City Waterford 1
Loans 1
City Galway
Loans 3
Any idea what kind of query I need to perform to get the count of distinct loans for each city?
I would guess, probably a COUNT (Distinct ID) with GROUP BY. Something like this:
SELECT city, COUNT(DISTINCT LoanApplicationID) as Loans
FROM tableName
GROUP BY city
Here is another approach for this question. I am adding this because using DISTINCT may cause performance issues for another example, especially for large databases. Good to keep in mind.
select city,count(LoanApplicationID) as Loans
from (
select LoanApplicationID, city
from tablename
group by LoanApplicationID, city
) t
group by city

SQL select count distinct

I want to know how many items of distinct name I have in my database.
When I use:
select count(distinct name) from products
I obviously gain only number of different, distinct names I have in my
database. I was experimenting with group by, but as a total beginner I
failed. I'll appreciate any help.
Group by name and use count() to get the counts for each group
select name, count(*)
from products
group by name
select count(name) as ct, name from products group by name
SELECT NAME, COUNT(*) FROM products GROUP BY name

postgis postgres count and group by column for ST_Distance function

This SQL produces the following:
SELECT city FROM travel_logs ORDER BY ST_Distance(travel_logs.start_point, ST_GeographyFromText('SRID=4326;POINT(101.652506 3.167610)'))
"Tshopo"
"Tshopo"
"Mongala"
"Haut-Komo"
This SQL produces the following:
SELECT city, count(*) AS count FROM travel_logs GROUP BY travel_logs.start_point, city ORDER BY ST_Distance(travel_logs.start_point, ST_GeographyFromText('SRID=4326;POINT(101.652506 3.167610)'))
"Tshopo";1
"Tshopo";1
"Mongala";1
"Haut-Komo";1
Basically, I want the result like this that groups by city and the number of times same city occurs. something like this
"Tshopo";2 <--- its summed up correctly
"Mongala";1
"Haut-Komo";1
Im not an expert on joins, subquery, would that help ? Thanks in advance.
this worked for me:
select city, count(*) as count
from
(SELECT city FROM travel_logs ORDER BY ST_Distance(travel_logs.start_point, ST_GeographyFromText('SRID=4326;POINT(101.652506 3.167610)'))
) as subquery_travel_logs_nearest group by city
Simple, plain SQL without a sub-query:
SELECT city, count(*)
FROM travel_logs
GROUP BY city
ORDER BY ST_Distance(start_point,
ST_GeographyFromText('SRID=4326;POINT(101.652506 3.167610)'));

PostgreSQL: get the min of a column with it's associated city

I have been at this for the past two hours and have tried many different ways in regards to subquery and joins. Here's the exact question "Get the name and city of customers who live in the city where the least number of products are made"
Here is a snapshot of the database tables
I know how to get the min
select min(quantity)
from products
but this returns just the min without the city attached to it so I can't search for the city in the customers table.
I have also tried group by and found it gave me 3 min's (one for each group of cities) which i believe may help me
select city,min(quantity)
from products
group by city
Putting everything together I got something that looks like
SELECT
c.name,c.city
FROM
customers c
INNER JOIN
(
SELECT
city,
MIN(quantity) AS min_quantity
FROM
products
GROUP BY
city
) AS SQ ON
SQ.city = c.city
But this returns multiple customers, which isn't correct. I assume by looking at the database the city when the lowest number of products seems to be Newark and there are no customers who reside in Newark so I assume again this query would result in 0 hits.Thank you for your time.
Example
Here is an example "Get the pids of products ordered through any agent who makes at least one order for a customer in Kyoto"
and the answer I provided is
select pid
from orders
inner join agents
on orders.aid = agents.aid
inner join customers
on customers.cid = orders.cid
where customers.city = 'Kyoto'
In Postgresql you have sophisticated tools, viz., windowing and CTEs.
WITH
find_least_sumq AS
(SELECT city, RANK() OVER ( PARTITION BY city ORDER BY SUM(quantity) ) AS r
FROM products)
SELECT name, city
FROM customers NATURAL JOIN find_least_sumq /* ON city */
WHERE r=1; /* rank 1 is smallest summed quantity including ties */
In Drew's answer, you are zeronig in on the cities where the smallest number of any particular item is made. I interpret the question as wanting the sum of items made in that city.
I guess it be something around this idea:
select customers.name, city.city, city.min
from customers
join (
select city, sum (quantity) as min
from products
group by city
--filter by the cities where the total_quantity = min_quantity
having sum (quantity) = (
--get the minimum quantity
select min(quantity) from products
)
) city on customers.city = city.city
This can be made so much simpler. Just sort the output by the field you want to get the minimum of.
SELECT city, quantity FROM customers ORDER BY quantity LIMIT 1;
I have just figured out my own answer. I guess taking a break and coming back to it was all I needed. For future readers this answer will use a subquery to help you get the min of a column and compare a different column (of that same row) to a different tables column.
This example is getting the city where the least number of products are made (quantity column) in the products table and comparing that city to the cities to the city column in the customers table, then printing the names and the city of those customers. (to help clarify, use the link in the original question to look at the structure of the database I am talking about) First step is to sum all the products to their respective cities, and then take the min of that, and then find the customers in that city.Here was my solution
with citySum as(
select city,sum(quantity) as sum
from products
group by city)
select name,city
from customers
where city
in
(select city
from citySum
where sum =(
select min(sum)
from citySum))
Here is another solution I have found today that works as well using only Sub queries
select c.name,c.city
from customers c
where c.city
in
(select city
from
(select p.city,sum(p.quantity) as lowestSum
from products p
group by p.city) summedCityQuantities
order by lowestsum asc
limit 1)

query in sql database

How do we find the top 2 most populated cities i.e where no. of customers are higher than any other
Assuming your schema looks like:
Customers
-City
-SSN
You should be able to simply use limit:
select City, count(SSN)
from Customers
group by City
order by count(SSN) desc
limit 2