Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT SQL Syntax For Count in WHERE clause

I'm trying to construct the correct sql statement (Oracle) to get the count of device_id's for each customer_id that is greater than a given value. For example, I want to know the customer_id's that have more than 3 device_ids. A single device_id can only have one customer_id associated to it, while a customer_id may have many device_ids.

Table:
device_id
customer_id
....

Data (device_id, customer_id):
00001, CUST1
00002, CUST1
00003, CUST1
00004, CUST1
00005, CUST2
00006, CUST2
like image 232
c12 Avatar asked Aug 15 '12 17:08

c12


People also ask

Can we use COUNT in WHERE clause in SQL?

SQL COUNT( ) with where clauseThe WHERE clause can be used along with SQL COUNT() function to select specific records from a table against a given condition.

How do I COUNT a SELECT statement in SQL?

SELECT COUNT(*) FROM table_name; The COUNT(*) function will return the total number of items in that group including NULL values. The FROM clause in SQL specifies which table we want to list. You can also use the ALL keyword in the COUNT function.

How do I add a COUNT to a SELECT query?

You need table aliases. So I think you want: Select ID as Num, (select Count(*) from TASK t where t.ID = o.ID) as Total from ORDER o; By the way, ORDER is a terrible name for a table because it is a reserved work in SQL.

What does SELECT COUNT (*) mean in SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.


1 Answers

To get the customers with more than 3 devices:

select customer_id, count(device_id)
from YourTable
Group by customer_id
having count(device_id) > 3
like image 77
Adriano Carneiro Avatar answered Oct 30 '22 13:10

Adriano Carneiro