How do I order countries by name in SQL? - sql

I have a problem with the following task from the platform Codesignal:
After some investigation, you've created a database containing a foreignCompetitors table, which has the following structure:
competitor: the name of the competitor;
country: the country in which the competitor is operating.
In your report, you need to include the number of competitors per country and an additional row at the bottom that contains a summary: ("Total:", total_number_of_competitors)
Given the foreignCompetitors table, compose the resulting table with two columns: country and competitors. The first column should contain the country name, and the second column should contain the number of competitors in this country. The table should be sorted by the country names in ascending order. In addition, it should have an extra row at the bottom with the summary, as described above.
Example
For the following table foreignCompetitors
my solution:
CREATE PROCEDURE solution()
BEGIN
(SELECT country, COUNT(*) AS competitors
FROM foreignCompetitors
GROUP BY country
ORDER BY country)
UNION
SELECT 'Total:', COUNT(*) FROM foreignCompetitors;
END
But my output is:
The result of the countries is not sorted by their names.
I cannot understand why is that even though I try to sort them with ORDER BY.

You want a GROUP BY WITH ROLLUP here:
SELECT COALESCE(country, 'Total:') AS country, COUNT(*) AS competitors
FROM foreignCompetitors
GROUP BY country WITH ROLLUP
ORDER BY country;
If you want to stick with your union approach, then you need to introduce a computed column into the union query which places the total row at the bottom of the result set. Consider:
SELECT country, competitors
FROM
(
SELECT country, COUNT(*) AS competitors, 1 AS pos
FROM foreignCompetitors
GROUP BY country
UNION ALL
SELECT 'Total:', COUNT(*), 2
FROM foreignCompetitors
) t
ORDER BY pos, country;

Related

Filter by number of occurrences in a SQL Table

Given the following table where the Name value might be repeated in multiple rows:
How can we determine how many times a Name value exists in the table and can we filter on names that have a specific number of occurrances.
For instance, how can I filter this table to show only names that appear twice?
You can use group by and having to exhibit names that appear twice in the table:
select name, count(*) cnt
from mytable
group by name
having count(*) = 2
Then if you want the overall count of names that appear twice, you can add another level of aggregation:
select count(*) cnt
from (
select name
from mytable
group by name
having count(*) = 2
) t
It sounds like you're looking for a histogram of the frequency of name counts. Something like this
with counts_cte(name, cnt) as (
select name, count(*)
from mytable
group by name)
select cnt, count(*) num_names
from counts_cte
group by cnt
order by 2 desc;
You need to use a GROUP BY clause to find counts of name repeated as
select name, count(*) AS Repeated
from Your_Table_Name
group by name;
If You want to show only those Which are repeated more than one times. Then use the below query which will show those occurrences which are there more than one times.
select name, count(*) AS Repeated
from Your_Table_Name
group by name having count(*) > 1;

Group By Clause, Do i have to call all rows what i using in Select?

Do I need to put all the column names in group by which I have select put in select?
for example in this simple query :
Select
CustomerID,
CompanyName,
ContactName,
ContactTitle,
City,
Country
From
Customers
Group By
Country,
CompanyName,
ContactName,
ContactTitle,
City,
Country,
CustomerID
I have to allways call same amount Group By what i used in Select?
If you're just selecting columns and you want the returned records to discard the exact duplicate rows? Then there are 2 methods.
1) group by
2) distinct
Your query doesn't use any of the aggregate functions like f.e. COUNT, MIN, MAX, SUM, ...
So your query could use DISTINCT instead of a GROUP BY.
select DISTINCT
CustomerID, CompanyName, ContactName, ContactTitle, City, Country
from Customers
But if CustomerID is a primary key, then CustomerID would already make the result unique.
So then this query doesn't need a GROUP BY or a DISTINCT to only get unique records.
select CustomerID, CompanyName, ContactName, ContactTitle, City, Country
from Customers
Note that one could have both DISTINCT and GROUP BY in the same query. But that's just pointless. A GROUP BY already enforces the uniqueness, so adding a DISTINCT to make them unique would just make the query slower for no reason.
As for the why all the columns in that select also have to be listed in the GROUP BY? Some databases, f.e. MySql can be more tolerant about not having to group on all columns. But it's a rule from one of the SQL Standards. So most databases enforce that. It's to avoid potential misleading results.
GROUP BY x, y means you want one result row per x and y. So if you have a table with bills, you could group by year and month for instance and thus get the number of bills (count(*)) and the total (sum(amount)) per month.
So the question is what rows do you want to see. A row per company (with the number of their customers) maybe? A row per city? The GROUP BY clause contains exactly those columns mentioned.
Your GROUP BY clause does exactly nothing, as select customers and you group by customer ID (which should be the customer table's primary key).

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

count value in three separate columns - Rails/SQL

Have a table roasts that has three columns country, country2, country3. The columns are for indicating which countries a blend of coffee comes from. It, therefore, goes that a country name could appear in any one of the three columns. Whilst I can do a count on any given column, I'd like to count how many times a value appears in all three of the country columns.
I'd like to do this in Rails/ActiveRecord. I've got as far as the below SQL, but this output isnt right:
SELECT country, country2, country3, COUNT(*) AS CountryCount FROM roasts GROUP BY country, country2, country3;
I suspect it's how I'm grouping.
You should have a table called something like CoffeeCountries that has one row per country for each blend. I would strongly recommend that you change the data structure.
With your data structure, you need to unpivot the data. Because your data is small and you are probably not familiar with lateral joins, I'm going to use the union all approach:
select country, count(*)
from ((select country1 as country from roasts) union all
(select country2 as country from roasts) union all
(select country3 as country from roasts)
) c
where country is not null
group by country
order by count(*) desc;
If you had a large table, I would recommend the lateral join. This version scans the table three times (once for each country).

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