在查询中包含CTE

时间:2013-01-23 16:04:04

标签: sql

我有以下代码可以完美运行。

我需要做的是将查询结果中的CTE结果作为查询结果中的列包含在查询中,但我无法解决这个问题。 有什么想法吗?

我想要的是这个:

select a, 
b, 
c, 
d,

WITH invoicedates AS (
    SELECT 
        ROW_NUMBER() OVER (ORDER BY Inv_Date DESC) AS RowNumber,
        inv_Date, INVIT_PARTNO
    FROM Invoices join InvoiceItems on invit_invno = inv_no
    WHERE invit_partno  = stock_no and inv_canind <> 'Y' and inv_date >= DATEADD(yy, -1, getdate())
)
SELECT
   AVG(DATEDIFF(DD, O2.Inv_Date, O1.Inv_Date)) AS AverageFrequency
FROM invoicedates O1
LEFT JOIN invoicedates O2
    ON O2.RowNumber = O1.RowNumber + 1

来自库存..........

给出b c d结果的结果输出

1 个答案:

答案 0 :(得分:0)

您应该能够重新排序使用CTE的方式:

    ; WITH invoicedates (RowNumber, inv_Date, INVIT_PARTNO) AS (
    SELECT 
        ROW_NUMBER() OVER (ORDER BY Inv_Date DESC) AS RowNumber,
        inv_Date, INVIT_PARTNO
    FROM Invoices join InvoiceItems on invit_invno = inv_no
    WHERE invit_partno  = stock_no and inv_canind <> 'Y' and inv_date >= DATEADD(yy, -1, getdate())
)

select a, 
b, 
c, 
d,
  AVG(DATEDIFF(DD, O2.Inv_Date, O1.Inv_Date)) AS AverageFrequency
FROM invoicedates O1
LEFT JOIN invoicedates O2
    ON O2.RowNumber = O1.RowNumber + 1