假设我有以下查询:
SELECT DISTINCT(Value1,value2,value3) From table1
并得到像
# value1 value2 value3
--------------------------------------
1. result1 result1 result2
2. result1 result2 result2
3. result5 result6 result7
如何添加一个额外的列,告诉我该值的唯一组合出现了多少次,例如(最后一列是它发生的次数):
# value1 value2 value3 #occurred
--------------------------------------
1. result1 result1 result2 15
2. result1 result2 result2 25
3. result5 result6 result7 35
最佳答案
使用group by
代替distinct
。然后,您可以使用count
。
select value1, value2, value3, count(*) as occurred
from table1
group by value1, value2, value3;
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
关于mysql - 计算SQL中不同列的数量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41968967/