0

I want to know how to query a table with both distinct and count feature.

For example:

SELECT ID, Email, ProductName, ProductModel
FROM Products

What can I do to pull data with Distinct feature on ID and per ID, Count of Email?

From something like:

    ID  email       ProductName 
0   a   [email protected]   apple       
1   b   [email protected]   orange
2   a   [email protected]   apple       
3   b   [email protected]   orange
4   c   [email protected]   grapefruit
5   a   [email protected]   apple       
6   b   [email protected]   orange
7   c   [email protected]   grapefruit
8   a   [email protected]   apple       
9   a   [email protected]   apple       
10  a   [email protected]   apple   

To something like:

    ID  Count       ProductName 
0   a   6       apple       
1   b   3       orange
2   c   2       grapefruit

Any help would be appreciated.

Dale K
  • 25,246
  • 15
  • 42
  • 71

1 Answers1

1
SELECT
ID,
count(distinct Email) as distinct_emails,
ProductName
FROM Products
group by ID,ProductName
barker
  • 1,005
  • 18
  • 36
  • Hey Barker, when the ID column is numeric, this code returns error: 'is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.' – Michael Yoo Oct 19 '21 at 02:34
  • did you add "product model" to your select statement and not in your group by statement? if so, see here https://stackoverflow.com/questions/13999817/reason-for-column-is-invalid-in-the-select-list-because-it-is-not-contained-in-e – barker Oct 19 '21 at 14:52
  • Aaah got it, thank you so much for the help. – Michael Yoo Oct 19 '21 at 15:37