0
select sl.*,

       (select pnd_invoiceno 
        from   PINVDET 
        where  PND_INVNO = sl.invno and

               abs(DATEDIFF(ss, pnd_date, sl.adjustedon)) = 
               (select min(abs(DATEDIFF(ss, pnd_date, sl.adjustedon)))
                from   PINVDET
                where  pnd_invno = sl.invno))

from   vwstocklog sl where sl.invno in (select invno from vwStockDiff) 
order  by sl.invno, sl.adjustedon

当我运行上面的查询时,我得到了错误:

在包含外部引用的聚合表达式中指定了多个列。如果要聚合的表达式包含外部引用,则该外部引用必须是表达式中引用的唯一列。

我理解它是说表达式min(abs(DATEDIFF(ss, pnd_date, sl.adjustedon)))是问题,因为它sl.adjustedmin()聚合中引用,除非它是聚合表达式中引用的唯一列,否则它不能这样做。我不确定如何修复它。

我在这里尝试做的是找到pnd_invoiceno记录中最接近同一项目pinvdet的值的值(并且我认识到这有可能链接到多个记录)。pnd_datesl.adjustedon

关于如何调整此查询以实现此目的的任何想法?

4

1 回答 1

2

第二次尝试(首先过滤):

With x as (
    select
        sl.invno,
        sl.adjustedon,
        p.pnd_invoiceno,
        rank() over (
            partition by sl.invno 
            order by abs(datediff(ss, p.pnd_date, sl.adjustedon))
       ) rk
    from
        vwstocklog sl 
            inner join
        pinvdet p
            on p.pnd_invno = sl.invno
    Where 
        Exists (
            Select
                'x'
            From
                vwStockDiff sd
            Where
                sl.invno = sd.invno
        )
)
Select
    x.invno,
    x.adjustedon,
    x.pnd_invoiceno
From
    x
Where
    x.rk = 1
order by 
    x.invno, 
    x.adjustedon

第一次尝试:

With x as (
    select
        sl.invno,
        sl.adjustedon,
        p.pnd_invoiceno,
        rank() over (
            partition by sl.invno 
            order by abs(datediff(ss, p.pnd_date, sl.adjustedon))
       ) rk
    from
        vwStockDiff sd
            inner join
        vwstocklog sl 
            on sl.invno = sd.invno
            inner join
        pinvdet p
            on p.pnd_invno = sl.invno
    )
Select
    x.invno,
    x.adjustedon,
    x.pnd_invoiceno
From
    x
Where
    x.rk = 1
order by 
    x.invno, 
    x.adjustedon

如果您碰巧有两次距离相等,这将为两者返回一行。如果您只喜欢 1,请替换rank()为。row_number()

SQLFiddle 目前似乎无法正常工作,因此我无法对此进行测试。可能有语法错误。

于 2013-09-27T20:52:19.900 回答