Reputation: 81
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.
Upvotes: 0
Views: 2036
Reputation: 4826
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
Upvotes: 0
Reputation: 32602
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 |
Upvotes: 1