简体   繁体   English

sql从特定字段计算唯一值

[英]sql count unique values from specific field

|from| to | 
|  7 |  9 |
|  7 |  9 |
|  3 |  9 |
|  3 |  2 |

Lets say I'm user 9 and want to find out how many user have wrote to me. 假设我是9位用户,想知道有多少用户给我写信。 With the query: 与查询:

SELECT COUNT(*) FROM tab WHERE to = 9;

I get 3 which means I got 3 new messages, but how to find out ho many users wrote me which would be 2 in this case? 我得到3,这意味着我收到了3条新消息,但是如何找出有多少用户写给我,在这种情况下为2?

You want count(distinct) : 你想要count(distinct)

SELECT COUNT(DISTINCT `from`)
FROM tab
WHERE `to` = 9;

If you want a more detailed result, you can use GROUP BY . 如果需要更详细的结果,可以使用GROUP BY

This way make it possible to see how many times the from user have sent messages to to user. 通过这种方式使人们有可能看到多少次from用户把邮件发送给to用户。

Eg 例如

SELECT from, to, count(*)
FROM tab
GROUP BY from, to

This will return: 这将返回:

|from  |to  |count(*) |
|------|----|---------|
|7     |9   |2        |
|3     |9   |1        |
|3     |2   |1        |

You can even insert your restriction, if you want: 如果需要,您甚至可以插入限制:

SELECT from, to, count(*)
FROM tab
GROUP BY from, to
HAVING to = 9

That would result in: 这将导致:

|from  |to  |count(*) |
|------|----|---------|
|7     |9   |2        |

Just an extra way to do it. 只是一种额外的方法。

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

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