SQL Server 2012:IIF 函数能否根据条件获取最后分配的值

SQL Server 2012: Can an IIF Function pick up the last assigned value based on a condition

假设我有一个 table 看起来像这样:

+---------+-----------+------------+
| Company |  Quantity |     Date   |
+---------+-----------+------------+
| A       |     10000 | 2016-08-01 |
| B       |     -5000 | 2016-08-01 |
| C       |      5000 | 2016-08-01 |
| A       |      5000 | 2016-08-02 |
| B       |     -2500 | 2016-08-02 |
| C       |      5000 | 2016-08-02 |
| A       |         0 | 2016-08-03 |
| B       |         0 | 2016-08-03 |
| C       |      5000 | 2016-08-03 |
+---------+-----------+------------+

我正在尝试创建一个包含名为 IssuerLS 的列的视图,如果数量为 +ve,则列值将为 'L',如果数量为 -ve,则列值将为 'S'。这部分使用 IIF 函数很容易,但如果数量为 0,我也想使用最后一个已知值。所以我的视图应该如下所示:

+---------+----------+------------+----------+
| Company | Quantity |    Date    | IssuerLS |
+---------+----------+------------+----------+
| A       |    10000 | 2016-08-01 | L        |
| B       |    -5000 | 2016-08-01 | S        |
| C       |     5000 | 2016-08-01 | L        |
| A       |     5000 | 2016-08-02 | L        |
| B       |    -2500 | 2016-08-02 | S        |
| C       |     5000 | 2016-08-02 | L        |
| A       |        0 | 2016-08-03 | L        |
| B       |        0 | 2016-08-03 | S        |
| C       |     5000 | 2016-08-03 | L        |
+---------+----------+------------+----------+

如果数量为 0,是否有办法让 IIF 函数为每个公司使用最后已知的 'L' 或 'S' 值?

谢谢。

可以使用大小写和外部应用来完成。

SELECT  *,
        CASE WHEN Quantity = 0 THEN CASE WHEN prevQuantity > 0 THEN 'L' ELSE 'S'END
             ELSE CASE WHEN Quantity > 0 THEN 'L' ELSE 'S' END
        END
FROM    Table1 t1
        OUTER APPLY (SELECT TOP 1
                            Quantity prevQuantity
                     FROM   Table1 t2
                     WHERE  t2.Company = t1.Company
                            AND t2.Date < t1.Date
                            AND t2.Quantity <> 0
                     ORDER BY [Date] DESC
                    ) t2

如果你想使用 IIF 那么

SELECT  *,
        IIF(Quantity <> 0, IIF(Quantity > 0, 'L','S'), IIF(prevQuantity > 0, 'L','S'))
FROM    Table1 t1
        CROSS APPLY (SELECT TOP 1
                            Quantity prevQuantity
                     FROM   Table1 t2
                     WHERE  t2.Company = t1.Company
                            AND t2.Date <= t1.Date
                            AND t2.Quantity <> 0
                     ORDER BY [Date] DESC
                    ) t2
    ;with cte
    as
    (select *,
    case 
    when qty>0 then 'l' 
    when qty<0 then 'S' 
    else null end as newval
     from #tmp
     )
     select c1.cmp,c1.qty,c1.date,
     case when newval is null then rplcval else newval end as somecol
      from cte  c1
     cross apply
     (
     select top 1 newval as rplcval from cte c2 where c2.date<=c1.date and c1.cmp = c2.cmp
order by date) b