简体   繁体   English

MySQL Count和Group By两个不同的列

[英]MySQL Count and Group By two distinct columns

I have a table recommendation with fields recommender , attractionid 我有一个字段recommenderattractionidrecommendation

I want to count the how many attractionid existed in the table group by the attractionid but if there are same pairs of recommender and attractionid they are counted as 1. For example, 我想算多少attractionid表组由存在attractionid但如果有相同的对recommenderattractionid他们被算作1。例如,

attractionid    recommender
      1               1
      1               2
      1               1
      2               3
      2               1
      2               2
      2               2
      2               2

expected result : 预期结果 :

 attractionid   count
      1            2
      2            3

the rows below should be counted as 1 下面的行应计为1

 attractionid    recommender
          1               1
          1               1
          2               2
          2               2
          2               2

Use distinct attractionid,recommender inside count function. 使用distinct attractionid,recommender in count函数

Query 询问

select attractionid,
count(distinct attractionid,recommender) as `count`
from recommendation
group by attractionid;

Try: 尝试:

select attractionid, count(recommender) cnt
from (
    select distinct attractionid, recommender
    from recommendation
) x
group by attractionid

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

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