如何在 LINQ 中进行聚合查询
我有一个带有金额字段的交易表,我想将金额字段拆分为借方和贷方。与下面的 SQL 查询等效的 LINQ 是什么?
Select sum(Amount < 0 ? Amount : 0) as Debit, sum(Amount > 0 ? 0 : Amount) as Credit
from transactions
where Account = strAccount
I have a transactions table with an amount field and I want to split the amount field into Debit and Credit. What is the LINQ equivalent to the SQL query below?
Select sum(Amount < 0 ? Amount : 0) as Debit, sum(Amount > 0 ? 0 : Amount) as Credit
from transactions
where Account = strAccount
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不幸的是,没有像获取单个结果时那样在单个 LINQ 查询中表达两种聚合的简单方法。这两个单独的查询将是:
或者:
我不能保证这些查询将在(例如)LINQ to SQL 中进行翻译,但我希望它们会如此。
如果您要查找所有帐户的贷方/借方,您可以在单个查询中执行此操作:
现在当然您可以使用:
那么会< /em> 是单个 SQL 语句,返回单个结果,如果找不到该帐户 ID,则返回 null。同样,您必须了解它实际上如何转换为 SQL。
Unfortunately there's no simple way of expressing both aggregations in a single LINQ query like that when it's fetching a single result. The two separate queries would be:
Or alternatively:
I can't guarantee that these will have translations in (say) LINQ to SQL, but I'd hope that they would.
If you were finding the credit / debit for all accounts, you could do that in a single query:
Now of course you could then use:
That then would be a single SQL statement, returning either a single result or null if it can't find that account ID. Again, you'd have to see how it actually translated to SQL.
您可以执行如下语句:
这转换为 SQL 为:
与原始的不太一样 - 您需要运行查询分析器才能了解
GROUP BY
的影响是否对你的数据库。You could do a statement like:
This translates to SQL as:
Not quite the same as the original - you'd need to run query analyser in order to understand if the impact of the
GROUP BY
was significant for your database.这样做的好处是只需在事务表上运行一次。但是,这会创建大量临时对象,每个事务对应一个临时对象。
如果您需要节省内存使用量,请对事务执行两次单独的传递:
This has the benefit of running over the transactions table only once. However, this creates a lot of temp objects, one for each transaction.
If you need to conserve memory usage, then do two separate passes over the transactions: