我有这个样本数据。
create table #student_info
(
transaction_id int identity(1,1)
,parent_id int
,transaction_date date
,[status] varchar(1)
)
insert into #student_info
(
parent_id
,transaction_date
,status
)
values(1,'2017-01-01','F'),(1,'2017-01-02','F'),(1,'2017-01-03','F'),
(1,'2017-01-04','F'),(1,'2017-01-05','F'),(1,'2017-01-06','T'),
(1,'2017-01-07','F'),(1,'2017-01-08','F'),(1,'2017-01-14','F'),
(1,'2017-01-15','F')
,(2,'2017-01-01','F'),(2,'2017-01-02','T'),(2,'2017-01-03','F'),
(2,'2017-01-09','F'),(2,'2017-01-10','F'),(2,'2017-01-11','T'),
(2,'2017-01-12','F'),(2,'2017-01-13','F')
select * from #student_info
我需要使用以下逻辑填充另一个附加列(transaction_type),
答案 0 :(得分:0)
查找状态为transaction_date
的每个parent_id
的第一个T
,然后使用Case
语句创建交易类型
这样的事情应该有所帮助
SELECT transaction_id,
parent_id,
transaction_date,
status,
transaction_type = CASE
WHEN transaction_date <= minT THEN 'Purchase'
WHEN Datediff(dd, minT, transaction_date) >= 7 THEN 'Renewal'
ELSE NULL
END
FROM (SELECT *,
minT = Min(CASE WHEN status = 'T' THEN transaction_date END)
OVER(partition BY parent_id) --first transaction_date for each parent id where status is T
FROM #student_info) a
结果:
+----------------+-----------+------------------+--------+------------------+
| transaction_id | parent_id | transaction_date | status | transaction_type |
+----------------+-----------+------------------+--------+------------------+
| 1 | 1 | 2017-01-01 | F | Purchase |
| 2 | 1 | 2017-01-02 | F | Purchase |
| 3 | 1 | 2017-01-03 | F | Purchase |
| 4 | 1 | 2017-01-04 | F | Purchase |
| 5 | 1 | 2017-01-05 | F | Purchase |
| 6 | 1 | 2017-01-06 | T | Purchase |
| 7 | 1 | 2017-01-07 | F | NULL |
| 8 | 1 | 2017-01-08 | F | NULL |
| 9 | 1 | 2017-01-14 | F | Renewal |
| 10 | 1 | 2017-01-15 | F | Renewal |
| 11 | 2 | 2017-01-01 | F | Purchase |
| 12 | 2 | 2017-01-02 | T | Purchase |
| 13 | 2 | 2017-01-03 | F | NULL |
| 14 | 2 | 2017-01-09 | F | Renewal |
| 15 | 2 | 2017-01-10 | F | Renewal |
| 16 | 2 | 2017-01-11 | T | Renewal |
| 17 | 2 | 2017-01-12 | F | Renewal |
| 18 | 2 | 2017-01-13 | F | Renewal |
+----------------+-----------+------------------+--------+------------------+