我在MySQL中有一个表,如下所示。
State marketId
CA Ind
CO Ind
CA Grp
CA Grp
我想选择数据作为计数和总计数(应如下所示)。
State marketId Count totalCountInd
CA Ind 1 2
CO Ind 1
目前我正在使用以下查询。那不是正确的输出。
select state,marketId,count(*),sum(CASE marketID WHEN 'ind' THEN 1 ELSE 0 END) AS totalCountInd from BatchReport where marketId='ind' group by state,marketId;
+-------+----------+----------+---------------+
| state | marketId | count(*) | totalCountInd |
+-------+----------+----------+---------------+
| CA | in | 1 | |
| CO | in | 1 | |
|+-------+----------+----------+---------------+
答案 0 :(得分:0)
这会给你一个更接近你想要的结果 区别在于它会重复totalCountInd
SELECT State, marketid, COUNT(1) as totalCount,
(
SELECT COUNT(1) FROM BatchReport
WHERE marketid = bp.marketid
) AS totalCountInd
FROM BatchReport bp
WHERE marketid = 'Ind'
GROUP BY State, marketid
结果如下:
State marketid totalCount totalCountInd
CA Ind 1 2
CO Ind 1 2
答案 1 :(得分:0)
如果您希望totalCOuntInd保持所有状态的计数与marketId“Ind”,那么在按州分组时,您无法以建议的格式获得此数据。
你可以做的是使用ROLLUP:
select state,marketId,count(*) as count
from BatchReport
where marketId='ind'
group by marketId, state with ROLLUP;
这将为您提供所有组列的arollup结果,如下所示:
marketId State Count
Ind CA 1
Ind CO 1
Ind NULL 2
NULL NULL 2
这也是唯一有道理的方法。