简体   繁体   English

非唯一列的选择和计数属性

[英]Select and count attribute for non-unique column

I have a table of persons and activities - neither column is unique. 我有一个人和活动的表-列都不是唯一的。 I need to rank every user by the count of distinct activities, eg: 我需要通过不同活动的数量对每个用户进行排名,例如:

_________________ 
|PERSON|ACTIVITY|
-----------------
|Lars  | Sleep  |
|James | Eat    |
|Lars  | Sleep  | 
|Lars  | Sleep  | 
|Kirk  | Shred  |
|James | Shred  |
-----------------

Lars appears thrice, but performs the same activity repeatedly. 拉尔斯三次出现,但反复进行相同的活动。 Kirk appears once, so he is identical to Lars in number of activities. 柯克出现一次,因此他在活动数量上与拉斯相同。 James performs two distinct activities, so he should be ranked the highest. 詹姆斯进行了两项不同的活动,因此他应该排名最高。

The expected output: 预期输出:

James - 2
Kirk - 1 
Lars - 1

(ordering of identical counts is irrelevant) (相同计数的顺序无关紧要)

The solution I have come up with involves applying DISTINCT to the person column and iterating over the names, selecting the activities for each and applying DISTINCT followed by COUNT. 我想出的解决方案包括将DISTINCT应用于人员列并遍历名称,为每个活动选择活动,然后应用DISTINCT,然后再加上COUNT。 It feels like there must be a better way. 感觉必须有更好的方法。

I think you just want count(distinct) : 我想你只想要count(distinct)

select person, count(distinct activity) as num_activities
from t
group by person
order by num_activities desc;

You could use GROUP BY function. 您可以使用GROUP BY函数。 SELECT PERSON, COUNT(DISTINCT ACTIVITY) AS count FROM YOUR TABLE GROUP BY PERSON ORDER BY count; 从您的表GROUP BY PERSON或ORDER BY COUNT中选择PERSON,COUNT(DISTINCT ACTIVITY)作为计数;

SELECT Person, COUNT(DISTINCT Activity) AS ActivityCount
FROM MyTable
GROUP BY Person
ORDER BY 2 DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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