-2

我在 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

我什至无法弄清楚如何编写查询,因为我不明白如何去做

4

2 回答 2

1

您可以使用窗口函数。假设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'
于 2020-11-13T09:32:43.913 回答
0
DECLARE @Suppliers table
(
    ID integer PRIMARY KEY CLUSTERED,
    Supplier char(6) NOT NULL,
    Supplier_Due smallmoney NOT NULL,
    [Date] date NOT NULL
);

INSERT @Suppliers
    (ID, Supplier, Supplier_Due, [Date])
VALUES
    (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');

SELECT
    S.ID, 
    S.Supplier, 
    S.Supplier_Due, 
    S.[Date],
    [Previous Due] =
        LAG(S.Supplier_Due, 1, 0) OVER (
            PARTITION BY S.Supplier
            ORDER BY S.[Date] ASC)
FROM @Suppliers AS S
WHERE
    S.[Date] = CONVERT(date, '2020-11-13', 121);

db<>小提琴演示

文档:LAG(Transact-SQL)

于 2020-11-13T09:38:27.900 回答