0

我有以下查询:

SELECT      ContractNr
,           SequenceNr
,           DurationBeginDate 
,           MIN(DurationBeginDate) OVER(PARTITION BY contractnr ORDER BY SEQUENCENR ASC) mindurdat
FROM        AccountContract
WHERE       ContractNr = 768

它返回以下结果:

ContractNr  SequenceNr DurationBeginDate            mindurdat
768         1          2008-03-08 00:00:00.0000000  2008-03-08 00:00:00.0000000
768         2          2008-06-08 00:00:00.0000000  2008-03-08 00:00:00.0000000
768         3          2008-09-08 00:00:00.0000000  2008-03-08 00:00:00.0000000
768         4          2008-12-08 00:00:00.0000000  2008-03-08 00:00:00.0000000
768         5          2007-06-08 00:00:00.0000000  2007-06-08 00:00:00.0000000

这不是我所期望的,我想要的mindurdat字段DurationBeginDate对应的是最低的SequenceNr. 换句话说,对于所有这些记录,2008-03-08 00:00:00.0000000 我应该不明白为什么此示例中的最后一条记录保留原始DurationBeginDate.

我知道我可以通过子查询获得正确的结果,但我想保持高效。

4

1 回答 1

0

当您在总和、最小值、最大值等中使用 order by 时,您会得到一个正在运行的聚合。所以它完全按照它的设计目的做。您可以使用子查询或连接来做您想做的事情:

-- Join
SELECT
    ac.ContractNr
    , ac.SequenceNr
    , ac.DurationBeginDate 
    , ao.DurationBeginDate FirstDurationBegin
FROM
    AccountContract ac
LEFT JOIN
    accountcontract ao
    ON 
        ao.contractnr = ac.contractnr
        AND 
        ao.sequencenr = 1
WHERE
    ac.ContractNr = 768

-- outer apply
SELECT
    ac.ContractNr
    , ac.SequenceNr
    , ac.DurationBeginDate 
    , aor.DurationBeginDate FirstDurationBegin
FROM
    AccountContract ac
OUTER APPLY
    (
        SELECT 
            ao.DurationBeginDate
        FROM 
            AccountContract ao
        WHERE
            ao.contractnr = ac.contractnr
            AND 
            ao.sequencenr = 1
    ) aor
WHERE
    ac.ContractNr = 768
于 2013-06-10T13:57:45.457 回答