[英]MySQL how to count from GROUP BY
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
等於2的公司1
和userid
是1
和3
?
select * from table where companyid = '1' group by date
只會返回mysql_num_row
等於1並返回12.8.14 | 1 | 1
12.8.14 | 1 | 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;
也嘗試這樣
select *,(select count(*) from table1 where companyid=a.companyid) as count
from t as a where companyid=1
你自找的:
select date,companyid,count(*)
from table
where userid = 1
group by date,companyid
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.