oracle--聚合函数和case when结合使用
需求:
1 根据客户信息表中信息比较出相应余额。
2 表中有客户号,余额,各个时间点的分区信息,每个分区中客户号唯一。
3 客户信息中分区有10、11、12、13、14、15。
4 得到每个比上日余额信息,如下面表样。
--创建测试表 客户信息表 CREATE TABLE CUST_INFO_TEST( CUST_NO VARCHAR2(5), AUM_EDU NUMBER, DT VARCHAR(10) ) --在表中插入测试数据 SELECT * FROM CUST_INFO_TEST FOR UPDATE --测试数据如下 CUST_NO AUM_EDU DT ---------- ---------- ----------- 1 11 20180610 2 22 20180610 3 33 20180610 1 11.11 20180611 2 22.22 20180611 3 33.33 20180611 1 11.21 20180612 2 22.32 20180612 3 33.33 20180612 1 11.44 20180613 2 22.44 20180613 3 33.44 20180613 --使用表的自关联实现 SELECT A1.CUST_NO ,A3.AUM_EDU - A2.AUM_EDU AS BSR_11 ,A4.AUM_EDU - A3.AUM_EDU AS BSR_12 ,A1.AUM_EDU - A4.AUM_EDU AS BSR_13 FROM CUST_INFO_TEST A1 LEFT JOIN CUST_INFO_TEST A2 ON A1.CUST_NO = A2.CUST_NO AND A2.DT = '20180610' LEFT JOIN CUST_INFO_TEST A3 ON A1.CUST_NO = A3.CUST_NO AND A3.DT = '20180611' LEFT JOIN CUST_INFO_TEST A4 ON A1.CUST_NO = A4.CUST_NO AND A4.DT = '20180612' WHERE A1.DT= '20180613'; --得到如下结果 CUST_NO BSR_11 BSR_12 BSR_13 -------- ---------- ---------- ---------- 1 0.11 0.1 0.23 2 0.22 0.1 0.12 3 0.33 0 0.11 --优化 SELECT CUST_NO ,SUM(CASE WHEN DT='20180611' THEN AUM_EDU ELSE 0 END - CASE WHEN DT='20180610' THEN AUM_EDU ELSE 0 END) AS BSR_11 ,SUM(CASE WHEN DT='20180612' THEN AUM_EDU ELSE 0 END - CASE WHEN DT='20180611' THEN AUM_EDU ELSE 0 END) AS BSR_12 ,SUM(CASE WHEN DT='20180613' THEN AUM_EDU ELSE 0 END - CASE WHEN DT='20180612' THEN AUM_EDU ELSE 0 END) AS BSR_13 FROM CUST_INFO_TEST WHERE DT IN ('20180610','20180611','20180612','20180613') GROUP BY CUST_NO --得到结果和上面一样 CUST_NO BSR_11 BSR_12 BSR_13 -------- ---------- ---------- ---------- 1 0.11 0.1 0.23 2 0.22 0.1 0.12 3 0.33 0 0.11
case when与聚合函数结合使用示例
CREATE TABLE TEST( CUST_NO NUMBER, ACT_TYPE VARCHAR2(50), ACT_TIME DATE); SELECT * FROM TEST FOR UPDATE; CUST_NO ACT_TYPE ACT_TIME ---------- ----------- ----------- 1 IN 2017/8/1 1 MSG 2018/8/10 2 MSG 2017/8/10 3 IN 2018/8/23 4 MSG 2018/8/17 5 IN 2018/8/10 5 MSG 2018/8/15 5 MSG 2017/8/1 5 IN 2018/8/6 SELECT CUST_NO ,SUM(CASE WHEN ACT_TYPE='IN' AND ACT_TIME>=DATE'2018-08-01' THEN 1 ELSE 0 END) AS IN_FLAG ,SUM(CASE WHEN ACT_TYPE='MSG' AND ACT_TIME>=DATE'2018-08-01' THEN 1 ELSE 0 END) AS MSG_FLAG FROM TEST GROUP BY CUST_NO --最后大于1就是对应的客户标签 CUST_NO IN_FLAG MSG_FLAG ---------- ---------- ---------- 1 0 1 2 0 0 4 0 1 5 2 1 3 1 0