1

我在 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 |               |
|+-------+----------+----------+---------------+
4

2 回答 2

0

如果您希望 totalCOuntInd 保存所有带有 marketId "Ind" 的状态的计数,那么在按状态分组时,您无法以建议的格式获得它。

你可以做的是使用 ROLLUP:

select state,marketId,count(*) as count
from BatchReport 
where marketId='ind' 
group by marketId, state with ROLLUP;

这将为您提供所有组列的汇总结果,如下所示:

marketId State Count
  Ind     CA    1                  
  Ind     CO    1
  Ind     NULL  2
  NULL    NULL  2

这也是唯一有意义的方法。

于 2013-04-19T09:29:13.897 回答
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
于 2013-04-19T06:19:29.637 回答