程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> 數據-SQL按時間抵消的查詢語句

數據-SQL按時間抵消的查詢語句

編輯:編程解疑
SQL按時間抵消的查詢語句

如何按時間順序用B表數據抵消A表數據
A表:
ID DATE MOUNT
A1 2015-01-01 200
A1 2015-02-02 200
A1 2015-03-10 300
A1 2015-03-20 100
B1 2015-01-02 100
B1 2015-02-25 300
B表
ID COUNT
A1 500
B1 300
得出如下結果:
ID DATE MOUNT
A1 2015-03-10 200
A1 2015-03-20 100
B1 2015-02-25 100
這樣按時間順序查出抵消後的數據,這樣的SQL語句怎麼寫,不要存儲過程

最佳回答:


 select t2.ID,t2.Date,t2.count
,(select sum(t1.count) from A t1 where DATE<=t2.DATE AND t1.ID=t2.ID) AS sumcount
,(select sum(t1.count) from A t1 where DATE<=t2.DATE AND t1.ID=t2.ID)-t3.count AS value
,(select sum(t1.count) from A t1 where DATE<t2.DATE AND t1.ID=t2.ID)-t3.count AS value2
,CASE WHEN (select sum(t1.count) from A t1 where DATE<t2.DATE AND t1.ID=t2.ID)-t3.count <0 THEN t2.count+((select sum(t1.count) from A t1 where DATE<t2.DATE AND t1.ID=t2.ID)-t3.count)
      ELSE t2.count
 END AS value3
from A t2, B t3
WHERE t2.ID=t3.ID AND ((select sum(t1.count) from A t1 where DATE<=t2.DATE AND t1.ID=t2.ID)-t3.count)>0
ORDER BY t2.ID,t2.Date
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved