0

Let's say I have the following query:

SELECT DISTINCT(Value1,value2,value3) From table1

and get something like

        #   value1  value2  value3
--------------------------------------
        1.  result1 result1 result2
        2.  result1 result2 result2
        3.  result5 result6 result7

How would I add an extra column that tells me how many times that unique combination of values appears, such as (last column is how many times it occurs):

 #    value1  value2  value3      #occurred
--------------------------------------
 1.  result1 result1 result2      15
 2.  result1 result2 result2      25
 3.  result5 result6 result7      35 
3
  • 3
    use count(*) grouping by those 3 columns. Commented Jan 31, 2017 at 22:54
  • 1
    Note that distinct is not a function. Instead, distinct alters the behavior of select. Think of it as select distinct, as opposed to select all, rather than choosing columns to select. You shouldn't put parens around it, that's some non-standard MySQL thing. Commented Jan 31, 2017 at 23:02
  • 2
    DISTINCT is a keyword that applies to the entire list of expressions, it's not a function. The parens aren't necessary. Extraneous parens aren't invalid, but there's no reason to include them. As vkp notes, remove the DISTINCT keyword, add a GROUP BY clause, and add a COUNT() aggregate to the SELECT list. Commented Jan 31, 2017 at 23:03

2 Answers 2

3
SELECT    Value1,value2,value3,count(*)
From      table1
group by  Value1,value2,value3
Sign up to request clarification or add additional context in comments.

Comments

2

Use a group by instead of distinct. Then you can use count.

select value1, value2, value3, count(*) as occurred
from table1
group by value1, value2, value3;

A demonstration in SQLite.

sqlite> select * from table1 order by value1, value2, value3;
value1      value2      value3    
----------  ----------  ----------
1           1           2         
1           1           2         
1           2           2         
1           2           2         
1           2           2         
5           6           7         

sqlite> select value1, value2, value3, count(*) as '#occurred' from table1 group by value1, value2, value3;
value1      value2      value3      #occurred 
----------  ----------  ----------  ----------
1           1           2           2         
1           2           2           3         
5           6           7           1         

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.