我在 sql 表中有以下数据,
ID | supplier | Supplier_Due | Date |
1 | S-0003 | 14850 |2020-11-09
2 | S-0003 | 850 |2020-11-09
3 | S-0003 | 21750 |2020-11-13
4 | S-0003 | 975 |2020-11-15
5 | S-0003 | 75 |2020-11-17
假设用户想要获取 2020-11-13 的数据,即
3 | S-0003 | 21750 |2020-11-13
但我想在指定的日期之前让以前的供应商到期
850
随着
3 | S-0003 | 21750 |2020-11-13
所以我想得到的实际查询是这个
ID | supplier | Supplier_Due | Date | Previous Due
3 | S-0003 | 21750 |2020-11-13 | 850
如果没有以前的到期我想回来
ID | supplier | Supplier_Due | Date | Previous Due
3 | S-0003 | 21750 |2020-11-13 | 0.00
我什至不知道如何编写查询,因为我不明白如何去做
您可以使用窗口函数。假设date
可用于一致地订购每个供应商的记录:
select *
from (
select t.*,
lag(supplier_due, 1, 0) over(partition by supplier order by date) as previous_due
from mytable t
) t
where date = '2020-11-13' and supplier = 'S-0003'
典型的替代方法是子查询或横向连接:
select t.*, coalesce(t1.supplier_due, 0) as previous_due
from mytable t
outer apply (
select top (1) supplier_due
from mytable t1
where t1.supplier = t.supplier and t1.date < t.date
order by t1.date desc
) t1
where date = '2020-11-13' and supplier = 'S-0003'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句