SQL WITH无法正常工作

时间:2016-02-29 10:48:21

标签: sql

我创建了一个查询,但它无效。任何人都可以向我解释这个吗?谢谢!

WITH    rows AS
    (
    SELECT   *, ROW_NUMBER() OVER (ORDER BY dtDeliveryDate) AS rn
    FROM    TCheckRecipient
    )

select avg(avarage) from(     
SELECT TCheck.iCheckId, AVG(DATEDIFF(minute, mc.dtDeliveryDate, mp.dtDeliveryDate))  as avarage
FROM    rows mc
left join TCheck on TCheck.iCheckId = mc.iCheckId

JOIN    rows mp
ON      mc.rn = mp.rn - 1
group by TCheck.iCheckId
)

我在做什么时

WITH    rows AS
        (
        SELECT   *, ROW_NUMBER() OVER (ORDER BY dtDeliveryDate) AS rn
        FROM    TCheckRecipient
        )

SELECT TCheck.iCheckId, AVG(DATEDIFF(minute, mc.dtDeliveryDate, mp.dtDeliveryDate))  as avarage
FROM    rows mc
left join TCheck on TCheck.iCheckId = mc.iCheckId

JOIN    rows mp
ON      mc.rn = mp.rn - 1
group by TCheck.iCheckId

效果很好。 但是当我试图平均那些回报时,我不能, 如果有人会回答我该怎么做,我会很高兴,谢谢

1 个答案:

答案 0 :(得分:2)

我会给出答案,以便我的评论更清晰。您可能只需要对内部查询进行别名。

WITH    rows AS
    (
    SELECT   *, ROW_NUMBER() OVER (ORDER BY dtDeliveryDate) AS rn
    FROM    TCheckRecipient
    )

select avg(avarage) from(     
SELECT TCheck.iCheckId, AVG(DATEDIFF(minute, mc.dtDeliveryDate, mp.dtDeliveryDate))  as avarage
FROM    rows mc
left join TCheck on TCheck.iCheckId = mc.iCheckId

JOIN    rows mp
ON      mc.rn = mp.rn - 1
group by TCheck.iCheckId
) A