简体   繁体   中英

Select query for Count in mysql

I have one table in MySQL as below.

State marketId 
CA     Ind
CO     Ind
CA     Grp
CA     Grp

I want to select the data as count and Total of count(should be as below).

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

Currently I am using below query. That is not giving the right output.

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'

Please suggest me.

What you want to achieve is not a good (and ideal) way to retrieve data using SQL:

You are trying to retrieve two different records together. You should retrieve those with different queries:

First retrieve count for each state and marketId:

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

Will give you

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

Then retrieve total count for each 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

Will give you

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

Or you can also get total count for each MarketId in rows like this:

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

Output:

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

See this SQLFiddle

Try this

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

EDIT

Check this SQLFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM