SQL Count Customers where Products are the same - sql

I have a problem. I have a SQL-database named customers with the 3 columns Country, CustomerID and Product. With that database, I want to count all the customers which bought the products bike, flask and helmet but grouped by the country as you can see in the following picture.
Is there a chance you can help me out with that? I guess I have to make a join on the same table and make a nested query with another select, but I don't really know how to do that.
I would be very thankful for your help!

You have to do aggregation in two steps. First find the customers with the 3 different products, then count these customers.
SELECT country, count(*)
FROM
(
SELECT country, CustomerID
FROM customers
WHERE product IN ('Bike','Flask','Helmet')
GROUP BY country, CustomerID
HAVING COUNT(distinct product) = 3
) dt
GROUP BY country

You might use HAVING clause along with GROUP BY while distinctly count for each customer after counted for those exact three products such as
SELECT Country, COUNT(DISTINCT CustomerID) AS Count
FROM customers
WHERE Product IN ('Bike','Flask','Helmet')
AND CustomerID IN ( SELECT CustomerID
FROM customers
GROUP BY CustomerID
HAVING COUNT(DISTINCT Product)=3 )
GROUP BY Country
Demo

Try this sql:
select Country,count(distinct CustomerID)
from customers
where Product in ('Bike','Flask','Helmet')
group by Country

select Country,count(distinct CustomerID)
from customers
where Product in ('Bike','Flask','Helmet')
group by Country

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING Product in ('Bike','Flask','Helmet');

Related

Using a COUNT in a WHERE Clause to find Products Purchased By One Customer

I have a PostgreSQL query similar to the following:
SELECT product, customer, COUNT(customer)
FROM table
WHERE COUNT (customer) = 1
I want the query to return a list of products that have only been bought by one customer. How can I do this without using a COUNT in there WHERE?
Many Thanks.
I see. You want products purchased by only one customer. The idea is:
SELECT product, MAX(customer) as customer, COUNT(*)
FROM table
GROUP BY product
HAVING MIN(customer) = MAX(customer);
Because there is only one customer, MAX(customer) is that customer. COUNT(*) is the number of products the customer purchased.
You must group by product and use a HAVING clause where you check if the product has been bought by only 1 customer:
SELECT product,
MAX(customer) AS customer -- you may remove this column if you don't need the customer also
FROM table
GROUP BY product
HAVING COUNT(DISTINCT customer) = 1

SQL should I use a subquery?

I need help on a course question for my school. So I am supposed to get two tables Seller & Item, and I need to return the most active seller based on the most items offered. I have the tables as links below.
How could I just return one record with the sellers ID# and Name? Do I need to do a subquery? Thank you so much in advance.
Actually this is a way to accomplish it via subquery. I don't know that any teacher would anticipate students using >= all though:
select s.sellerid, min(s.name) as name
from seller s inner join item i on i.sellerid = s.sellerid
group by s.sellerid
having count(*) >= all (
select count(*)
from item
group by sellerid
)
You can also do it doubly=nested without even needing aliases!
select * from seller where sellerid in
(
select sellerid from item group by sellerid
having count(*) >= all (select count(*) from item group by sellerid)
)

How to Count Items that are return by a Group By Statements

Im currently trying to create a query in SQL that groups a list of products by vendor ID and then by categoryID an returns the groups that only have more than one product listed in them.
This is what I have so far:
SELECT Product.VendorID, CategoryID, Count (*) as NumProducts, avg(ProductPrice) as AveragePrice
From Product, Vendor
Where ProductPrice>50
Group By Product.VendorID, CategoryID
Having Count (Product.ProductID)>1;
My problem is that it returns categories that also have only one item in them.
You would seem to need a join. My guess is:
SELECT Product.VendorID, CategoryID, Count(*) as NumProducts, avg(ProductPrice) as AveragePrice
From Product inner join
Vendor
on Product.VendorId = Vendor.VendorId
Where ProductPrice>50
Group By Product.VendorID, CategoryID
Having Count(*) > 1;
It is not clear where the columns are coming from in your query, but you may not need the Vendor table at all.

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)

Count number of users from a certain country

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