Neokoenig
Neokoenig

Reputation: 1102

Subquery with COUNT (mysql)

I have the following table:

id   | user | createdAt           | pstatus  
-------------------------------------------------------
287  | Foo  | 2013-08-01 17:19:24 | PLAYING  
286  | Foo  | 2013-08-01 17:18:24 | IDLE  
285  | Foo  | 2013-08-01 17:17:24 | PLAYING  
284  | Foo  | 2013-08-01 17:16:24 | BUFFERING 
283  | Foo  | 2013-08-01 17:15:24 | STOPPED

How can I query this table to produce the following result? Essentially, I need to get the total number of different values of pstatus per user, per day.

User | logdate    | playCount | idleCount | bufferCount | StopCount
-------------------------------------------------------------------
Foo  | 2013-08-01 |         48|        62 |           0 |         4
Foo  | 2013-08-02 |         25|        22 |           0 |         0
Bar  | 2013-08-02 |         22|        32 |           5 |         4
Bar  | 2013-08-03 |         44|        11 |           1 |         0
Foo  | 2013-08-03 |         32|        03 |           0 |         0

I know I can use DATE(createdAt) to get the date per day instead of a timestamp, but I'm struggling with how essential merge the following into a single query:

COUNT(pstatus) AS playCount WHERE pstatus = "PLAYING";
COUNT(pstatus) AS idleCount WHERE pstatus = "IDLE";
COUNT(pstatus) AS bufferCount WHERE pstatus = "BUFFERING";
COUNT(pstatus) AS StopCount WHERE pstatus = "STOPPED";

I'm pretty sure it needs to be subquery, but struggling with the syntax!

Upvotes: 1

Views: 86

Answers (2)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

You can use SUM with a condition this will result in a boolean and will give you the count based on conditions

SELECT
DATE(createdAt) logdate,    
SUM(pstatus = "PLAYING") playCount 
,SUM(pstatus = "IDLE") idleCount 
,SUM(pstatus = "BUFFERING") bufferCount 
,SUM(pstatus = "STOPPED") StopCount
FROM `table`
GROUP BY `User`,DATE(`createdAt`)

Demo

Upvotes: 3

echo_Me
echo_Me

Reputation: 37233

try this:

   SELECT 
  SUM(CASE 
         WHEN pstatus = "PLAYING" THEN 1
         ELSE 0
       END) AS sumPLAYING,
   SUM(CASE 
         WHEN pstatus = "IDLE" THEN 1
         ELSE 0
       END) AS sumIDLE,

   SUM(CASE 
         WHEN pstatus = "BUFFERING" THEN 1
         ELSE 0
       END) AS sumBUFFERING,
   SUM(CASE 
         WHEN pstatus = "STOPPED" THEN 1
         ELSE 0
       END) AS sumSTOPPED
FROM YOUR_TABLE 

Upvotes: 0

Related Questions