我收到此错误
Msg 102,Level 15,State 1,Line 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
我试图在seq前面添加select我得到这些错误:
Msg 4104,Level 16,State 1,Line 3
多部分标识符&#34; t.CustID&#34;无法受约束。Msg 4104,Level 16,State 1,Line 4
多部分标识符&#34; t.InvoiceID&#34;无法受约束。Msg 4104,Level 16,State 1,Line 5
多部分标识符&#34; t.Date&#34;无法受约束。Msg 4104,Level 16,State 1,Line 6
多部分标识符&#34; t.S_Type&#34;无法受约束。Msg 4104,Level 16,State 1,Line 34
多部分标识符&#34; .Debit&#34;无法受约束。
答案 0 :(得分:1)
您的请求seq=...
开头的代码片段无效。您的查询可以使用cte。
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;
在借记之前还有一个 c 缺失。
感谢a_horse_with_no_name。