简体   繁体   中英

How to count how many times certain values appear in a table in SQL and return that number in a column?

I've used the COUNT function to determine how many rows there are in a table or how often a value appears in a table.

However, I want to return the 'count' for multiple values in a table as a seperate column.

Say we a have a customer table with columns; Customer ID #, Name, Phone Number.
Say we also have a sales table with columns: Customer ID, Item Purchased, Date

I would like my query to return a column for customer ID and a column for # of times that customer ID appeared in the sales table. I would like to do this for all of my customer IDs at once--any tips?

You want to use GROUP BY

Select Count(*), CustomerID
from Sales
GROUP BY CustomerID

You can use group by :

select   customer_id,
         count(*)
from     sales  
group by customer_id

This will return a row by customer ID with the count of how many matching items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM