看板 Database 關於我們 聯絡資訊
假設: 提款 Table 叫 table1 存款 Table 叫 table2 ;with tb1 as ( select t1.TransactionID,t2.Amount, datediff(day,t2.Date,t1.Date) as day from table1 t1 inner join table2 t2 on t1.AccountID = t2.AccountID and datediff(day,t2.Date,t1.Date) between 1 and 7 ) select TransactionID, isnull([1],0), isnull([2],0), isnull([3],0), isnull([4],0), isnull([5],0), isnull([6],0), isnull([7],0) from tb1 pivot ( sum(Amount) for day in ([1],[2],[3],[4],[5],[6],[7]) ) as pvt ※ 引述《x9060000456 (你好)》之銘言: : 資料庫名稱:MS SQL : 資料庫版本:MS SQL 2017 : 內容/問題描述: : 大家安安大家好 : 小弟第一次在DB版發文, : 請各位前輩多多指教! : 最近在處理存提款資料, : 有兩個table, : 資料類似如下: : 提款Table : AccountID TransactionID 提款Date : 001 A1 2018-05-20 : 001 A2 2018-05-21 : 002 A3 2018-05-20 : 003 A4 2018-05-23 : 存款Table : AccountID 存款Date Amount : 001 2018-04-20 1 : 001 2018-05-14 2 : 001 2018-05-14 3 : 001 2018-05-15 1 : 001 2018-05-17 1 : 001 2018-05-22 1 : 002 2018-05-13 1 : 002 2018-05-16 1 : 003 2018-05-18 1 : 003 2018-05-22 1 : 003 2018-05-25 1 : 本人想抓取 提款Table 中每筆 TransactionID 的 : 提款ID 往回 7 天的 存款Table 每天的 Amount 總和, : 像是 TransactionID 為 A1 時, 提款Date 往回七天是 : 2018-05-19 ~ 2018-05-13, 故對應回存款Table的AccountID和存款Date : 則會得到如下: : TransactionID 前1天Sum 前2天Sum 前3天Sum 前4天Sum 前5天Sum 前6天Sum 前7天Sum : A1 0 0 1 0 1 5 0 : A2 0 0 0 1 0 1 5 : A3 0 0 0 1 0 0 1 : A4 1 0 0 0 0 0 0 : 在懇請各位大大提供一些想法XD : 大感謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.232.39.112 ※ 文章網址: https://www.ptt.cc/bbs/Database/M.1527224114.A.4F0.html
x9060000456: 感謝C大, 太強大了! 05/26 10:39