简体   繁体   中英

SQL: Display Distinct Items and number of instances of something else for it

I have a table called Inventory that has 2 columns called Item_ID and Color. There are many cases where the same Item_ID has multiple listings with different colors:

Item_ID(1, 1) Color(Blue, Green)

I have to display a listing of all the DISTINCT Item_ID's and also the number of colors each distinct Item_ID comes in.

I know to use SELECT DISTINCT Item_ID AS Item_ID FROM Inventory; in order to get a listing of all the distinct Item_IDs, but I have no clue how to get a listing of the amount of colors each distinct Item_ID comes in.

For the Table, I would like to display: Item_ID: 1, Colors: 2

You can do group by on item_ID to count colors per item

    SELECT DISTINCT Item_ID AS    
    Item_ID , COUNT(Color) as   
    ColorCount FROM Inventory
    GROUP BY Item_ID

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