How to count the number of rows matching certain values? - mysql

Actually I have a table now:
[Person Table]:
ID Name age City
====================================
1 Jack 14 New York
2 Mike 15 LA
3 Ben 16 Beijing
?
100 Lee 32 Singapore
(total record = 100)
(Id is Primary Key)
Please provide a SQL script to query customer that his/her city occurs in the table more than or equal to 6.
Example:
The number of customer that live in New York is 10
The number of customer that live in LA=5
The number of customer that live in Beijing=6.
So in this example the output should be all customer that live in New York and Beijing only.

Something like this should work:
select * from customers
join (select city from customers group by city having count(*) >= 6)
as city_count
on customers.city = city_count.city;
All you are doing is creating a list of the cities that have six or more customers and then using that to filter the original customers table.
Link to SQL Fiddle - using 2 as the threshold

Related

LIMIT and Group By? How do I return the lowest 100 earning customers by country? SQL

Hi I’ve a table database1
3 columns : customer_id , income , country
Customer_id
1001
1002
...
Income
5000
6000
7000
Country
SG
HK
VN
...
How do I write a query that returns the lowest 100 earning customers per country?
Is it possible to return:
Customer ID | country code
1003 SG
1004 SG
...
1007 VN
...
So on
Thanks!
On mySQL 8 you can leverage a window function for this:
SELECT * FROM
(
SELECT
country,
customer_id,
row_number() over(partition by country order by income asc) earn_rank
FROM table
)x
WHERE x.earn_rank <= 100
You can conceive that this window function will sort the rows by country then by income, then start counting up from 1. Each time the country changes the row numbering starts over from 1 again. This means that for every country there will be a row numbered 1 (with the lowest income), and a 2, 3 etc. If we then wrap it up in another outer query that selects only rows where the number is less than 101 we get 100 rows per country

MS Access: Count instances over field based on record-level criteria

I need a query to count the number of orders shipped to each state for each customer. So, let's say John had 5 orders: 2 to Florida, 2 to Alaska, and 1 to Kansas. How do I get those counts for each Customer. I have a query that provides me Customer and Order delivery state, but I cannot figure out how to get the counts. I am looking for something like:
>John FL 2
>John FL 2
>John AK 2
>John KS 1
>John AK 2
>...[Next Customer]...
Thank you.
You need to group it by customer and state and count based on this:
SELECT Customer, State, Count(*) AS Amount
FROM Orders
GROUP BY Customer, State
The resulting calculated field, is named Amount in this example.

How to use a text (string) to depict no relationship between tables from Oracle to HTML?

I am getting data from an Oracle database into an HTML table, I am replacing nulls with strings but I am just wondering if there is a way to add a string into html such as 'Unavailable' where there is no relationship
NB: PLACENAME_ID is a foreign key in the OWNER table
place = """ SELECT coalesce(NAME,'Unknown') FROM PLACES WHERE PLACENAME_ID = """ + str(pid)
ownerquery = """ SELECT NAME, FROM OWNER WHERE PLACENAME_ID = """ + str(pid)
The second query is invalid; comma between NAME and FROM?
Anyway: what you described sounds like outer join which enables you to display "something" when there's "nothing". Here's an example, based on Scott's schema:
There are 4 departments. Pay attention to department DEPTNO = 40, as there are no employees that work there:
SQL> select * from dept where deptno = 40;
DEPTNO DNAME LOC
---------- -------------- -------------
40 OPERATIONS BOSTON
SQL> select count(*) from emp where deptno = 40;
COUNT(*)
----------
0
In order to display it as well (when joined to the EMP table), you'd use outer join:
SQL> select d.deptno, d.dname, e.ename
2 from dept d left join emp e on e.deptno = d.deptno
3 order by d.deptno;
DEPTNO DNAME ENAME
---------- -------------- ----------
10 ACCOUNTING KING
10 ACCOUNTING CLARK
10 ACCOUNTING MILLER
20 RESEARCH FORD
20 RESEARCH SMITH
20 RESEARCH JONES
30 SALES JAMES
30 SALES TURNER
30 SALES MARTIN
30 SALES WARD
30 SALES ALLEN
30 SALES BLAKE
40 OPERATIONS --> this!
13 rows selected.
SQL>
If there was no outer join, you wouldn't even see the last row.
Now, how to implement that to your code, I wouldn't know - it doesn't even have any kind of a join, but it should as you mentioned a "foreign key". We don't have that tables' description either.

How to select one column with all distinct values based on some clause

I essentially like to have one query which I'll execute one time and like to have the result (no multiple query execution) and definitely, the query should use simple MySQL structure (no complex/advanced structure to be used like BEGIN, loop, cursor).
Say I've two tables.
1st Table = Country (id(PK), name);
2nd Table = Businessman (id(PK), name, city, country_id(FK))
Like to SELECT all countries, whose businessmen are from distinct cities. No two businessmen exist in one country, who are from the same city. If so, that country will not be selected by the SELECT clause.
Country
id name
1 India
2 China
3 Bahrain
4 Finland
5 Germany
6 France
Businessman
id name city country_id
1 BM1 Kolkata 1
2 BM2 Delhi 1
3 BM3 Mumbai 1
4 BM4 Beijing 2
5 BM5 Paris 6
6 BM6 Beijing 2
7 BM7 Forssa 4
8 BM8 Anqing 2
9 BM9 Berlin 5
10 BM10 Riffa 3
11 BM11 Nice 6
12 BM12 Helsinki 4
13 BM13 Bremen 5
14 BM14 Wiesbaden 5
15 BM15 Angers 6
16 BM16 Sitra  3
17 BM17 Adliya 3
18 BM18 Caen 6
19 BM19 Jinjiang 2
20 BM20 Tubli 3
21 BM21 Duisburg 5
22 BM22 Helsinki 4
23 BM23 Kaarina 4
24 BM24 Bonn 5
25 BM25 Kemi 4
In this respect, China and Finland shouldn't be listed.
I've attempted using count and group by, but no luck.
Can you please help me to build up this query.
Here it is, all you need is to join Businessman table and count cities and distinct cities and if they equal that means all businessmen are from different cities:
SELECT
c.`id`,
c.`name`,
COUNT(b.`id`) AS BusinessmanCount,
COUNT(b.`city`) AS CityCount,
COUNT(DISTINCT b.`city`) AS DistinctCityCount
FROM `countries` c
INNER JOIN Businessman b ON c.`id` = b.`country_id`
GROUP BY c.`id`
HAVING CityCount = DistinctCityCount
For minified version what you exactly need:
SELECT
c.`id`,
c.`name`
FROM `countries` c
INNER JOIN Businessman b ON c.`id` = b.`country_id`
GROUP BY c.`id`
HAVING COUNT(b.`city`) = COUNT(DISTINCT b.`city`)
Well, I think we should have waited for you to show your own query, because one learns best from mistakes and their explanations. However, now that you've got answers already:
Yes, you need group by and count. I'd group by cities to see if I got duplicates. Then select countries and exclude those that have duplicate cities.
select *
from country
where id not in
(
select country_id
from businessmen
group by city, country_id
having count(*) > 1
);
You need either nested aggregations:
select *
from Country
where id in
(
select country_id
from
(
select city, country_id,
count(*) as cnt -- get the number of rows per country/city
from Businessman
group by city, country_id
) as dt
group by country_id
having max(cnt) = 1 -- return only those countries where all counts are unique
)
Or compare two counts:
select *
from Country
where id in
(
select country_id
from Businessman
group by country_id
having count(*) = count(distinct city) -- number of cities is equal to umber of rows
)

How to regroup records with different values in one SQL query

Let's say I have the following table :
Name - Country - Age
--------------------
Toto - Switzerland - 10
Titi - France - 12
Tata - Italy - 21
Tutu - England - 13
Tete - Italy - 14
I want to create a sql query as simple as possible to regroup people living in defined grouped countries like :
Group A = Switzerland + Italy
Group B = France + England
I don't know how to create a group withn my records with a column that could have multiple different values in the same group...
Could somebody help me with this ?
More information : SQL Server 2008 database.
You mean like this?
SELECT COUNT(Name), GroupA, GroupB FROM
(`SELECT Name, Country, Age,
Country='Switzerland' OR Country='Italy' As GroupA,
Country='France' OR Country='England' As GroupB)
Group By GroupA, GroupB
Select * from (select *,case when Country ='Switzerland' then 'A'
when Country ='Italy' then 'A'
when Country ='France' then 'B'
when Country ='England' then 'B'
else 'C' end) classification from table1)
order by classification
This will group the ppl as per your criteria. If this grouping is static you can have seprate table and use inner join. That will make query more readable