2016-01-12 185 views
0

我得到這個錯誤的SQL Server CTE查詢語法錯誤

消息102,級別15,狀態1,行1個
附近有語法錯誤 '='。

從該查詢:

seq = row_number() over 
(
    partition by t.CustID 
    order by t.InvoiceID, 
      t.Date, 
      CASE WHEN t.S_Type = 'Receipt Voucher' THEN 1 ELSE 2 END 
) 

; 

WITH cte 
AS (
    SELECT CustID, 
     [InvoiceID], 
     S_Type, 
     DATE, 
     Debit, 
     Credit, 
     seq = row_number() OVER (
      PARTITION BY CustID 
      ORDER BY InvoiceID, 
       DATE, 
       CASE 
        WHEN S_Type = 'Receipt Voucher' 
         THEN 1 
        ELSE 2 
        END 
      ) 
    FROM Statement 
    ) 
SELECT c.[InvoiceID], 
    c.S_Type AS Type, 
    c.DATE, 
    c.Debit, 
    c.Credit, 
    b.Balance 
FROM cte c 
CROSS APPLY (
    SELECT Balance = SUM(Debit) - SUM(Credit) 
    FROM cte AS x 
    WHERE x.CustID = c.CustID 
     AND x.seq <= c.seq 
    ) b 
WHERE c.CustID = '48' 
    AND DATE BETWEEN '2015-01-01' 
     AND '2016-01-01' 
ORDER BY seq 

我已嘗試添加選擇在前期序列的我得到這些錯誤:

消息4104,級別16,狀態1,3號線
無法綁定多部分標識符「t.CustID」。

Msg 4104,Level 16,State 1,Line 4
無法綁定多部分標識符「t.InvoiceID」。

Msg 4104,Level 16,State 1,Line 5
無法綁定多部分標識符「t.Date」。

Msg 4104,Level 16,State 1,Line 6
無法綁定多部分標識符「t.S_Type」。

Msg 4104,Level 16,State 1,Line 34
無法綁定多部分標識符「.Debit」。

+1

我對你發佈的代碼感到困惑。你真的在執行'WITH cte'上面的片段嗎? –

回答

1

您在請求開始時有一段代碼seq=...,這是無效的。您的查詢可以使用在cte中計算的seq

WITH cte 
AS (
    SELECT CustID, 
     [InvoiceID], 
     S_Type, 
     DATE, 
     Debit, 
     Credit, 
     seq = row_number() OVER (
      PARTITION BY CustID 
      ORDER BY InvoiceID, 
      DATE, 
      CASE 
       WHEN S_Type = 'Receipt Voucher' 
        THEN 1 
       ELSE 2 
       END 
      ) 
    FROM Statement 
    ) 
SELECT c.[InvoiceID], 
    c.S_Type AS Type, 
    c.DATE, 
    c.Debit, 
    c.Credit, 
    b.Balance 
FROM cte c 
CROSS APPLY (
    SELECT Balance = SUM(Debit) - SUM(Credit) 
    FROM cte AS x 
    WHERE x.CustID = c.CustID 
     AND x.seq <= c.seq 
    ) b 
WHERE c.CustID = '48' 
    AND DATE BETWEEN '2015-01-01' 
    AND '2016-01-01' 

ORDER BY c.seq; 

還有借記之前缺少Ç

感謝a_horse_with_no_name。

+0

我仍然得到錯誤,你可以提供完整的代碼,可能我錯誤地應用 – Ayman

+0

@Ayman我編輯我的答案,並糾正另一個小問題 – grahamj42

+0

謝謝,但仍然有問題錯誤味精「t.CustID,t.InvoiceID,t.Date ,t.S_Type「無法綁定 – Ayman