3

Consider the following table

tweets
---------------------------------
tweet_id  nyse_date   class  type
---------------------------------
1         2011-03-12  2      0
2         2011-03-12  1      1
3         2011-03-12  1      0
4         2011-03-12  1      0
5         2011-03-12  0      0
6         2011-03-12  1      0
7         2011-03-12  3      2
8         2011-03-12  3      0

Each tweet has assigned a 'class', which is either 1, 2 or 3 and a 'type', being 0, 1 or 2. I want to have an overview of the number of tweets in each class and type, as follows:

nyse_date   class1  class2  class3  type0  type1  type2
-------------------------------------------------------
2011-03-12  3       1       2       6      1      1

I started with the following query (grouping by date because the real table has many different dates):

SELECT
  nyse_date,
  COUNT(class) AS class1 FROM tweets WHERE class = 1,
  COUNT(class) AS class2 FROM tweets WHERE class = 2
GROUP BY
  nyse_date ASC

The expected output was

nyse_date   class1  class2
--------------------------
2011-03-12  3       1     

but I got an error instead. I believe this has to do with the fact that I can only use one WHERE clause per query (and I'm using 2) but I don't know what the alternative would be. Do you?

Any help is greatly appreciated :-)

4

3 に答える 3

6

これを試して:

SELECT
  nyse_date,
  SUM(class = 1) AS class1,
  SUM(class = 2) AS class2,
  SUM(class = 3) AS class3
FROM 
  tweets
GROUP BY
  nyse_date ASC

class = 1ブール式であり、TRUEまたはに値を付けFALSEます。ATRUEはに等しい1。したがって、SUM実際に使用するということは、「条件が成立するすべての行をカウントする」ことを意味します。

于 2012-07-14T13:06:55.497 に答える
0

Use the GROUP_CONCAT aggregate function in MySql:

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

于 2012-07-14T13:04:24.843 に答える
0

Does this work?

SELECT nyse_date, SUM( IF( class =1, 1, 0 ) ) AS class1, SUM( IF( class =2, 1, 0 ) ) AS class2
FROM tweets
GROUP BY nyse_date
于 2012-07-14T13:19:09.397 に答える