2015-05-28 65 views
1

我有這樣的表結構我需要一個查詢多個列每個日期在同一個表

Date  | Success  | No of success tran.| Failed  | No. of failed tran 
29/05/2015 | Total Amount | count success tran.|total amount| count failed tran 

我想

  1. 「日期」有datetime
  2. 「成功」有成功總金額。
  3. 「成功交易數量」具有總成功數量。
  4. 「失敗」的總失敗金額。
  5. 「失敗事務數量」具有總失敗數量計數。
+0

你的意思是一組按日期(如29/05/2015 00:00:00)與其他列上的總和?在創建表格stmt plop,所以我們可以看到結構 – Drew

+0

我的意思是日期喜歡29:05:2015 00:00:00 –

+0

所以你可能有幾行在那裏某個日期,如29/05/2015?如果是這樣,請使用'As'來選擇日期,sum(a),sum(b)等組,並使用'As'來獲得適當的總和列名稱 – Drew

回答

0
create table test999 
(id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
thedate datetime not null, 
status varchar(20) not null, 
amount decimal (10,2) not null 
) 


insert into test999 (thedate,status,amount) values (now(),'success',9283.92); 
insert into test999 (thedate,status,amount) values (now(),'failed',283.22); 
insert into test999 (thedate,status,amount) values (now(),'success',3283.92); 
insert into test999 (thedate,status,amount) values (now(),'failed',26.26); 
insert into test999 (thedate,status,amount) values (now(),'success',9083.02); 
insert into test999 (thedate,status,amount) values (now(),'failed',20093.12); 
insert into test999 (thedate,status,amount) values (DATE_SUB(NOW(), INTERVAL 17 DAY),'failed',26.26); 
insert into test999 (thedate,status,amount) values (DATE_SUB(NOW(), INTERVAL 17 DAY),'success',9083.02); 
insert into test999 (thedate,status,amount) values (DATE_SUB(NOW(), INTERVAL 17 DAY),'failed',20093.12); 

SELECT 
    date(thedate), 
    SUM(CASE WHEN status='success' then 1 else 0 end 
     ) AS success_count, 
    SUM(CASE WHEN status='success' then amount else 0 end 
     ) AS success_amount, 
    SUM(CASE WHEN status='failed' then 1 else 0 end 
     ) AS failed_count, 
    SUM(CASE WHEN status='failed' then amount else 0 end 
     ) AS failed_amount 
FROM test999 
group by date(thedate) 
order by date(thedate) 

date | success_count | success_amt | failed_count | failed_amt 
2015-05-11 1 9083.02 2 20119.38 
2015-05-28 3 21650.86 3 20402.60 
相關問題