2016-03-23 80 views
1

我有一個MySQL查詢(由史記創建): -Mysql的數量和總排

SELECT  'blr' AS Location,  COUNT(*) AS playCnt,  (select count(*) from blr_skip WHERE blr_skip_dt like '%2016-03-20%') as skipCnt FROM blr_play WHERE blr_play_dt like '%2016-03-20%' UNION SELECT  'chen' AS Location,  COUNT(*) AS playCnt,  (select count(*) from chen_skip WHERE chen_skip_dt like '%2016-03-20%') as skipCnt FROM chen_play WHERE chen_play_dt like '%2016-03-20%'; 

這使輸出這樣的: -

+----------+---------+---------+ 
| Location | playCnt | skipCnt | 
+----------+---------+---------+ 
| blr  |  25 |  8 | 
| chen  |  12 |  1 | 
+----------+---------+---------+ 

我想補充的多一個排在這樣的專欄結尾總: -

+----------+---------+---------+ 
| Location | playCnt | skipCnt | 
+----------+---------+---------+ 
| blr  |  25 |  8 | 
| chen  |  12 |  1 | 
+----------+---------+---------+ 
|Total  |  37 |  9 | 
+----------+---------+---------+ 

回答

2

試試這個:

SELECT 
    IFNULL(Location, 'Total') AS Location, 
    SUM(playCnt) AS playCnt, 
    SUM(skipCnt) AS playCnt 
FROM 
(
    SELECT  'blr' AS Location,  COUNT(*) AS playCnt,  (select count(*) from blr_skip WHERE blr_skip_dt like '%2016-03-20%') as skipCnt 
    FROM blr_play 
    WHERE blr_play_dt like '%2016-03-20%' 
    UNION 
    SELECT  'chen' AS Location,  COUNT(*) AS playCnt,  (select count(*) from chen_skip WHERE chen_skip_dt like '%2016-03-20%') as skipCnt 
    FROM chen_play 
    WHERE chen_play_dt like '%2016-03-20%' 
) t1 
GROUP BY Location WITH ROLLUP; 
+0

我沒有得到適當的總數。如果你想要mysql的轉儲文件,那麼這裏是鏈接: - https://www.mediafire.com/?444n3tvcvj24dpm –

+0

確定只是作出了一個小的變化,你的查詢就像魅力增加總和(playcnt),sum(skipcnt) –