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'

我的问题是,我怎样才能在一个查询中进行此操作,并且仍然使用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

您可以通过将结果连接在一起来做到这一点。但是,这两个查询中的逻辑非常相似,因此您可以将它们组合成一个聚合查询:

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 回答