DB2同比環比2(with as )
之前的那種同比環比方式,效率不高。資料量一大,就不好用了。因此用with as 寫了另一個求同比環比的sql。
sql
creat table xxx as
(with m(time,ticket_type,business_name,amount) as (select createtime,ticket_type,business_name,ticket_amount from xxx order by createtime)
select cur.*,
tb.amount tb_amount from m cur
left join m tb
on
cur.business_name=tb.business_name and cur.ticket_type=tb.ticket_type and substr(to_date(cur.time,'yyyy-mm-dd')-1 year,1,10)=tb.time
order by time desc);
分析:
- with as 片段,提高效率。將 時間、票類、商家、分成放在m中
- ** to_date(cur.time,'yyyy-mm-dd')-1 year** 求去年同期時間
注意:
由於時間有多個,需要有其他欄位將分成唯一確定,因此要想分成和哪些有關。是由票類商家確定的。所以
cur.business_name=tb.business_name and cur.ticket_type=tb.ticket_type
否則,可能出現多對一,使結果不唯一。
結果
TIME TICKET_TYPE BUSINESS_NAME AMOUNT TB_AMOUNT
2017-03-01 套票 xxx 31.00 67.40
2017-03-01 套票 xxx 62.00 133.00
2017-03-01 套票 XXX 18.60 39.80
2017-03-01 套票 XXX 344.80 750.90
2017-03-01 套票 XXX 485.00 1103.20
2017-03-01 套票 XXX 93.00 200.00
2017-03-01 套票 XXX 95.20 217.30
2017-03-01 套票 XXX18.60 39.80
2017-03-01 XX XXX 122.78 305.71
2017-03-01 XX XXX45.00 105.00
將結果插入表中
create table xx (createtime varchar(64),ticket_type varchar(128),business_name varchar(128),amount numeric(18,2),b_amount numeric(18,2));
insert into xx
with m(time,ticket_type,business_name,amount)
as (select create time,ticket_type,business_name,ticket_amount from XXX order by createtime)
select cur.*,
tb.amount tb_amount from m cur
left join m tb
on cur.business_name=tb.business_name and cur.ticket_type=tb.ticket_type and substr(to_date(cur.time,'yyyy-mm-dd')-1 year,1,10)=tb.time order by time desc ;
select * from xx;
相關文章
- DB2 Linux環境安裝DB2Linux
- DB2 和SQL Server自增列比較DB2SQLServer
- DB2常用函式與Oracle比較TIDB2函式Oracle
- DB2環境變數管理方法集TODB2變數
- mysql 求分組中位數、環比、同比、中位數的環比、同比MySql
- DB2 WLMDB2
- db2 -attribute of key are miss in result set . db2 錯誤DB2
- Hive之同比環比的計算Hive
- db2 reorg,runstatsDB2
- DB2的STMTIDDB2
- Db2 備份DB2
- DB2 安裝DB2
- DB2 SQL改寫DB2SQL
- DB2 HADR效能分析DB2
- The Db2 Recovery History FileDB2
- db2 load dumpfile for exceptionDB2Exception
- Oracle連線Db2OracleDB2
- 常用的DB2命令DB2
- DB2 export詳解DB2Export
- db2 資料庫DB2資料庫
- db2 資訊中心DB2
- 哪個 BI 產品能實現同比環比?
- Golang 如何操作DB2的?GolangDB2
- db2 hadr_spool_limitDB2MIT
- db2大表統計DB2
- DB2常用命令DB2
- DB2 Port (Network Security) RequirementsDB2UIREM
- DB2效能最佳化DB2
- DB2日誌相關DB2
- CTR:2021年2月廣告市場花費同比增長68.4% 環比減少5.6%
- 實現同比、環比計算的N種姿勢
- db2 客戶端安裝DB2客戶端
- DB2 HADR的heartbeat檢測DB2
- DB2備份與恢復DB2
- DB2執行計劃分析DB2
- db2 建立bufferpool,表空間DB2
- db2 鎖分析 DB2_CAPTURE_LOCKTIMEOUT使用DB2APT
- db2 事件監視器型別DB2事件型別
- 如何寫出更快的 SQL (db2)SQLDB2