0

station_idを介してグループ化してクエリを実行するために使用するこのテーブルがあります。

+------------------+---------------+------+-----+---------+-------+
| Field            | Type          | Null | Key | Default | Extra |
+------------------+---------------+------+-----+---------+-------+
| id               | varchar(50)   | NO   | PRI | NULL    |       |
| station_id       | tinyint(3)    | NO   |     | NULL    |       |
| game_type_id     | smallint(1)   | NO   | MUL | NULL    |       |
| price            | decimal(10,2) | YES  |     | 0.00    |       |
| date_created     | datetime      | YES  | MUL | NULL    |       |
| bet_no1          | tinyint(2)    | YES  |     | 0       |       |
| bet_no2          | tinyint(2)    | YES  |     | 0       |       |
+------------------+---------------+------+-----+---------+-------+

これは、 GROUP BY station_idを使用してテーブルに表示するために使用するクエリです。

SELECT station_id,
COUNT(*) as bet_counts,
FORMAT(SUM(price),2) as gross
FROM bets 
WHERE bet_void=0 
AND date_created >= '2013-02-12 00:00:00' 
AND date_created < '2013-02-23 00:00:00' 
GROUP BY station_id

クエリは私に与えます。

+------------+------------+-------+
| station_id | bet_counts | gross |
+------------+------------+-------+
|          1 |         14 | 16.00 |
|          2 |          5 | 5.00  |
|          7 |         11 | 11.00 |
+------------+------------+-------+

しかし、各station_idから特定のベット ( game_type_id )をカウントする別のクエリもあります。私は通常、ループ ステートメント内でこれをクエリします。

SELECT COUNT(*) as count
FROM bets
WHERE game_type_id = 1
AND station_id = {station_id from first query}
AND date_created >= '2013-02-12 00:00:00'
AND date_created < '2013-02-23 00:00:00'

私の質問は、これを 1 つのクエリで作成し、GROUP BY station_idを使用して、各game_type_idのベット数を取得するにはどうすればよいですか? この結果のようなもの。

+------------+------------+-------+-------------------------+-------------------------+
| station_id | bet_counts | gross | count_of_game_type_id_1 | count_of_game_type_id_2 |
+------------+------------+-------+-------------------------+-------------------------+
|          1 |         14 | 16.00 |                      10 |                       4 |
|          2 |          5 | 5.00  |                       3 |                       2 |
|          7 |         11 | 11.00 |                      11 |                       0 |
+------------+------------+-------+-------------------------+-------------------------+
4

1 に答える 1

1

You can do this by joining the results together. However, the logic in the two queries is very similar, so you can combine them into a single aggregation query:

SELECT station_id,sum(case when bet_void = 0 then 1 else 0 end) as bet_counts,
       FORMAT(SUM(case when bet_void = 0 then price else 0 end),2) as gross,
       sum(case when game_type_id = 1 then 1 else 0 end) as count
FROM bets b
where date_created >= '2013-02-12 00:00:00' AND date_created < '2013-02-23 00:00:00'
GROUP BY station_id
于 2013-02-22T03:17:28.937 に答える