MySQL如何从GROUP BY中计数

时间:2014-08-22 04:15:55

标签: mysql

date    | userid | companyid  
12.8.14 |   1    |    1  
12.8.14 |   2    |    2  
12.8.14 |   3    |    1
我有一张上面的桌子。通过普通查询可以很容易地计算表中公司1的数量。

我的问题是:如果我的查询是select * from table where companyid = '1' group by date,我如何才能使公司mysql_num_row 1等于2,userid 1 3 {1}}?

select * from table where companyid = '1' group by date只会归还我 mysql_num_row等于1,结果为12.8.14 | 1 | 1

3 个答案:

答案 0 :(得分:1)

您可以嵌套查询以获取公司一个条目的总和,然后将该嵌套查询加入外部查询:

SELECT ABB2.*, ABB1.mysql_num_row
FROM `table` AS ABB2
  JOIN 
      (SELECT companyid, COUNT(userid) AS mysql_num_row
      FROM `table`
      GROUP BY companyid) AS ABB1 ON ABB1.companyid = ABB2.companyid
WHERE ABB2.companyid = 1;

Example

答案 1 :(得分:0)

也是这样尝试

select *,(select count(*) from table1 where companyid=a.companyid) as count 
from t  as a where companyid=1

答案 2 :(得分:0)

你想:

select date,companyid,count(*)
from table
where userid = 1
group by date,companyid