我在SQL Server 2008中查询使用此SQL语句:
select
sum(tax + debit) + (select isnull(sum(tax + credit), 0)
from BILLTRANSACTION
where (BillClass = 2 or BillClass = 5 or BillClass = 6)
and (ClientID = 101383)
and datediff(month, StatementOrRecptDate, '3-31-2018') >= 0
and datediff(month, BeginDate, '3-31-2018') = 1)
from
BILLTRANSACTION
where
(ClientID = 101383)
and datediff(month, EndDate, '3-31-2018') = 1
它有效 - 现在我正在尝试将它应用于我在vb.net中的代码,但它无效。
顺便说一句,我有一个本地的SQL Server Compact数据库,并且我针对它运行了我的查询,但是它没有工作。
这是我的错误的屏幕截图:https://ibb.co/fKBkHy
答案 0 :(得分:0)
聚合通常不允许使用子查询。因此,只需将表达式移到from
子句:
select (sum(bt.tax + bt.debit) + coalesce(bt2.tax_credit, 0))
from billtransaction bt cross join
(select sum(bt2.tax + bt2.credit) as tax_credit
from billtransaction bt2
where bt2.BillClass in (2, 5, 6) and
ClientID = 101383 and
datediff(month, StatementOrRecptDate, '2018-03-31') >= 0 and
datediff(month, BeginDate, '2018-03-31') = 1
) bt2
where bt.ClientID = 101383 and
datediff(month, bt.EndDate, '2018-03-31') = 1;
注意:
ISNULL()
替换为COALESCE()
。后者是ANSI标准。OR
替换了IN
表达式的序列 - 更容易编写,阅读和维护。