oracle 分組求和一個小例子,oracle分組求和

來源:互聯網
上載者:User

oracle 分組求和一個小例子,oracle分組求和

2015年4月9日 天氣冷

表gw_log設計如下:
Name         Type          Nullable Default Comments   ------------ ------------- -------- ------- ---------- ID           VARCHAR2(50)                   訊息id     SERVICE_ID   VARCHAR2(20)  Y                服務ID     REQ_TIME     DATE          Y                請求時間   INVOKE_TIME  DATE          Y                調用時間   STATUS       CHAR(1)       Y        '0'     0:失敗,1:成功 RESP_TIME    DATE          Y                回應時間   USER_NAME    VARCHAR2(20)  Y                使用者名稱     SERVICE_TIME DATE          Y                調用服務結束時間 DESCN        VARCHAR2(256) Y                 描述 
統計每天驗證通過及不通過的總記錄數:成功的sql語句:
--方式1select req_time,       sum(decode(status, '0', 1, 0)) fail,       sum(decode(status, '1', 1, 0)) success  from gw_log group by req_time;

執行結果如下:

當然,用了decode()函數,那也可以用case函數了。

 --方式2 select distinct a.req_time, a.fail, b.success  from (select req_time,count(*) fail          from gw_log         where status = '0'         group by req_time) a        right join         (select req_time, count(*) success          from gw_log         where status = '1'         group by req_time) b on a.req_time = b.req_time【參考:select * from  (select * from emp) e cross join   (select * from book) b】

執行結果如下:

count 無記錄未返回0, 因為有 group by 子句的.
如果是不分組(即沒有 Group By) 那是一定會返回一個 0 的.
要讓有 分組 的count返回 0 , 則需要使用外串連

失敗的sql語句:
--方式3 select *    from (select a.req_time, count(*) success            from gw_log a           where a.status = '1'           group by req_time          union          select b.req_time, count(*) fail            from gw_log b           where b.status = '0'           group by b.req_time) g

執行結果如下:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.