案例,select有条件的需求

在Excel查询中操作时,我需要一个条件语句来读取一个字段,并根据该值将另一个字段设置为负(或不)。

我的SQl代码如下:

SELECT "_bvSTTransactionsFull".txdate, SUM("_bvSTTransactionsFull".debit) AS 'TOTALDebit', SUM("_bvSTTransactionsFull".credit) AS 'TOTALCredit', SUM("_bvSTTransactionsFull".tax_amount) AS 'TOTALTax_Amount', SUM("_bvSTTransactionsFull".VALUE) AS 'TOTALValue', SUM("_bvSTTransactionsFull".actualvalue) AS 'TOTALActualValue', SUM("_bvSTTransactionsFull".actualsalesvalue) AS 'TOTALActualSalesValue', SUM("_bvSTTransactionsFull".profit) AS 'TOTALProfit' FROM sqlschema.dbo."_bvSTTransactionsFull" "_bvSTTransactionsFull" WHERE ( "_bvSTTransactionsFull".txdate >=? AND "_bvSTTransactionsFull".txdate <=? ) GROUP BY "_bvSTTransactionsFull".txdate, "_bvSTTransactionsFull".description HAVING ( "_bvSTTransactionsFull".description LIKE 'POS Sale' ) OR ( "_bvSTTransactionsFull".description LIKE 'POS Return' ) ORDER BY "_bvSTTransactionsFull".txdate 

我需要select查询来查看名为“ ActualQuantity ”(表中“ _bvSTTransactionsFull ”),如果该字段是<0,则Tax_Amount = -(Tax_Amount) ,或者if ActualQuantity >=0, then Tax_Amount = Tax_Amount

请注意查询是“求和”的,所以我认为这个条件方面需要在求和之前进行处理。 查询将大约100 000条logging汇总为每日总计。

 SELECT "_bvSTTransactionsFull".txdate, SUM("_bvSTTransactionsFull".debit) AS 'TOTALDebit', SUM("_bvSTTransactionsFull".credit) AS 'TOTALCredit', SUM(case when "_bvSTTransactionsFull".ActualQuantity >= 0 then "_bvSTTransactionsFull".tax_amount else - "_bvSTTransactionsFull".tax_amount end) AS 'TOTALTax_Amount', SUM("_bvSTTransactionsFull".VALUE) AS 'TOTALValue', SUM("_bvSTTransactionsFull".actualvalue) AS 'TOTALActualValue', SUM("_bvSTTransactionsFull".actualsalesvalue) AS 'TOTALActualSalesValue', SUM("_bvSTTransactionsFull".profit) AS 'TOTALProfit' FROM sqlschema.dbo."_bvSTTransactionsFull" "_bvSTTransactionsFull" WHERE ( "_bvSTTransactionsFull".txdate >=? AND "_bvSTTransactionsFull".txdate <=? ) GROUP BY "_bvSTTransactionsFull".txdate, "_bvSTTransactionsFull".description HAVING ( "_bvSTTransactionsFull".description LIKE 'POS Sale' ) OR ( "_bvSTTransactionsFull".description LIKE 'POS Return' ) ORDER BY "_bvSTTransactionsFull".txdate 

如果ActualQuantity可能为零,但同一行中的taxAmount也为零,则可以使用sign函数更改tax_amount的符号:

 sign(ActualQuantity) * tax_amount 

更新:

所以我认为MS Query在使用graphics无法显示的查询中使用参数时遇到问题。 解决方法是用一些常量replace参数,将工作簿保存为XML并将常量更改为“?”。 有一个链接显示VBA代码现场replace ,但你将不得不弄清楚它是如何工作的,因为我不知道VBA那么多。

更新2:

另一方面,最简单的方法是在数据库中创build视图。