0

我在 MySQL 中有一张表,如下所示。

State marketId 
CA     Ind
CO     Ind
CA     Grp
CA     Grp

我想选择数据作为计数和计数总数(应如下所示)。

State marketId Count totalCountInd  totalCountGrp
  CA     Ind    1        2               2
  CO     Ind    1
  CA     Grp    2

目前我正在使用以下查询。那没有给出正确的输出。

select state, marketId, count(*) as 'count', (select count(1) from BatchReport where marketId='Ind') as 'total' from  BatchReport group by state,marketId  having marketId='Ind'  
union  
select state, marketId, count(*) as 'count1', (select count(1) from BatchReport where marketId='Grp') as 'total1' from BatchReport group by state,marketId  having marketId='Grp'

请给我建议。

4

2 回答 2

1

您想要实现的不是使用 SQL 检索数据的好(和理想)方法:

您正在尝试同时检索两个不同的记录。您应该检索具有不同查询的那些:

首先检索每个 state 和 marketId 的计数:

SELECT State, marketId, COUNT(marketId) AS Count
FROM BatchReport
GROUP BY State, marketID

会给你

| STATE | MARKETID | COUNT(MARKETID) |
--------------------------------------
|    CA |      Grp |               2 |
|    CA |      Ind |               1 |
|    CO |      Ind |               1 |

然后检索每个 marketId 的总数:

SELECT
SUM(CASE MarketID WHEN 'Ind' THEN 1 ELSE 0 END) AS totalCountInd 
,SUM(CASE MarketID WHEN 'Grp' THEN 1 ELSE 0 END) AS totalCountGrp
FROM BatchReport

会给你

| TOTALCOUNTIND | TOTALCOUNTGRP |
---------------------------------
|             2 |             2 |

或者,您还可以像这样在行中获取每个 MarketId 的总数:

SELECT
MarketId, COUNT(MarketID) AS Count
FROM BatchReport
GROUP BY MarketId;

输出:

| MARKETID | COUNT |
--------------------
|      Grp |     2 |
|      Ind |     2 |

看到这个 SQLFiddle

于 2013-04-18T05:08:48.740 回答
0

试试这个

SELECT State, marketId, totalCount
    ,CASE WHEN rownum = 1 THEN (SELECT COUNT(marketId) FROM BatchReport WHERE marketId = 'Ind') END AS totalCountInd
    ,CASE WHEN rownum = 1 THEN (SELECT COUNT(marketId) FROM BatchReport WHERE marketId = 'Grp') END AS totalCountGrp 
FROM 
(
    SELECT @rownum:=@rownum+1 'rownum',B.* FROM
    (
      SELECT State, marketId, COUNT(marketId) AS totalCount
      FROM BatchReport
      GROUP BY State, marketID
    ) B, (SELECT @rownum:=0) r

) Result_BatchReport

编辑

检查这个SQLFiddle

于 2013-04-18T09:59:00.183 回答