[英]cte using sql server
When I try to run the below query 当我尝试运行以下查询时
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,
.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
I get the following error: 我收到以下错误:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '='.
消息102,级别15,状态1,行1'='附近的语法不正确。 Msg 156, Level 15, State 1, Line 21 Incorrect syntax near the keyword 'ORDER'.
消息156,级别15,状态1,第21行关键字“ ORDER”附近的语法错误。
The problem is here in your Cte
: 问题在您的
Cte
:
...
seq = row_number() OVER (
PARTITION BY CustID,
ORDER BY InvoiceID,
DATE,
CASE
WHEN S_Type = 'Receipt Voucher'
THEN 1
ELSE 2
END
)
...
You have a ,
after PARTITION BY CustID
, the correct syntax is without that comma: 在
PARTITION BY CustID
之后,
您有一个,
正确的语法是没有逗号:
...
seq = row_number() OVER (
PARTITION BY CustID
ORDER BY InvoiceID,
DATE,
CASE
WHEN S_Type = 'Receipt Voucher'
THEN 1
ELSE 2
END
)
...
Another issue you have in your query is that you do not have an alias for the Debit
field in the final SELECT
: 您的查询中存在的另一个问题是,在最终的
SELECT
中您没有Debit
字段的别名:
SELECT c.[InvoiceID],
c.S_Type AS Type,
c.DATE,
.Debit, <-- Here
c.Credit,
b.Balance
The full query would be as follows: 完整的查询如下:
;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(X.Debit) - Sum(X.Credit)
From Cte X
Where X.CustId = C.CustId
And X.seq <= C.seq
) B
Where C.CustID = '48'
And C.Date Between '2015-01-01' And '2016-01-01'
Order By C.seq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.