2013-02-22 80 views
0

我有這張表,我用它來通過station_id進行分組查詢。如何結合這兩個MySQL查詢使用Group By

+------------------+---------------+------+-----+---------+-------+ 
| 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 | 
+------------+------------+-------+ 

,但我也有另外一個查詢計算每一個具體的賭注(game_type_id)從每個station_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 | 
+------------+------------+-------+-------------------------+-------------------------+ 

回答

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 
+0

哇謝謝!我還添加了SUM(game_type_id = 1且bet_void = 0 then 1 else 0 end時)作爲game_type_1_count,'** bet_void = 0 ** – tiltdown 2013-02-22 03:32:57