Re: [SQL ] 筛选每笔资料日期的前七天资料

楼主: cutekid (可爱小孩子)   2018-05-25 12:55:12
假设: 提款 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
: 大感谢!
作者: x9060000456 (你好)   2018-05-26 10:39:00
感谢C大, 太强大了!

Links booklink

Contact Us: admin [ a t ] ucptt.com