mysql选择计数不同的行数量

时间:2016-02-29 11:49:39

标签: mysql sql

是否可以在MySQL中计算具有5行或更多行且具有特定值的行?

它将与distinct完全相同,但会忽略少于5行的值

此外,如果它确实找到了5行以上的值,我只希望它计为1。

如果不清楚或不够清楚,请告诉我

Table:
ID 
1001
1001
1001
1001
1001
1002
1002
1003
1003
1003
1003
1003
1004

我希望此表计算具有5行或更多行的唯一ID的数量。 所以我希望这返回2

更新:

$var = 5;
try{

  $results = $db->prepare("SELECT COUNT(*) as Total FROM(
    SELECT user_id as YourCount
    FROM card_stats
    GROUP BY user_id
    HAVING count(*) >= ?)");

  $results->bindParam(1,$var);//value
  $results->execute();
  $hold = $results->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
  echo "Data could not be retrieved from the database.";
  exit();
}
var_dump($hold);

我尝试了以上但它给了我一个错误。我把东西搞砸了吗?

更新2: 这对我有用

$var1 = 1101;
$var2 = 5;
try{

  $results = $db->prepare("SELECT count(*)
            FROM (SELECT user_id, count(*) as cnt
                  FROM card_stats
                  WHERE deck_id = ?
                  GROUP BY user_id
                 ) card_stats
            WHERE cnt >= ?;");

  $results->bindParam(1,$var1);//value
  $results->bindParam(2,$var2);//value
  $results->execute();
  $hold = $results->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
  echo "Data could not be retrieved from the database.";
  exit();
}
var_dump($hold);

2 个答案:

答案 0 :(得分:2)

类似于:

SELECT COUNT(*) as TotalMoreThenFive FROM(
    SELECT value as YourCnt
    FROM YourTable
    GROUP BY value
    HAVING count(*) >= 5)

having子句只过滤那些有5行或更多行的人,然后用另一个查询包装它来计算有多少这样的值。

答案 1 :(得分:1)

对于您澄清的问题,请使用子查询:

select count(*)
from (select col, count(*) as cnt
      from t
      group by col
     ) t
where cnt >= 5;