如何解决如何对包括 Datalog/DataScript/Datomic 上缺少属性的实体的值求和
我正在学习 Datalog/DataScript/Datomic。为此,我在 DataScript 上设置了一个简单的分类帐数据库来使用。到目前为止,它基本上由一组帐户和具有属性 :entry.record/account
和 :entry.record/amount
的记录列表组成。现在我试图通过对每个帐户的所有 :entry.record/amount
求和来获得所有帐户的余额。此查询为我提供了在分类帐上有记录的所有帐户的余额:
(d/q '[:find ?account ?account-name (sum ?amount)
:with ?record
:in $
:where [?account :account/name ?account-name]
[?record :entry.record/account ?account]
[?record :entry.record/amount ?amount]]
@conn)
但是我有一些帐户还没有注册任何记录,而且它们没有出现在这里。我想进行一个包含它们的查询,以 0 值列出。我一直在使用 or-join
和 missing?
将这些帐户包含在查询中,但我不知道如何将帐户的金额设为 0。例如,这个查询:
(d/q '[:find ?account ?account-name (sum ?amount)
:with ?record
:in $
:where [?account :account/name ?account-name]
(or-join [?record]
(and [?record :entry.record/account ?account]
[?record :entry.record/amount ?amount])
[(missing? $ ?record :entry.record/account)])]
@conn)
抛出消息 Query for unkNown vars: [?amount]
的异常,因为 or-join
的第二部分无法为 ?amount
赋值。
解决方法
Datomic 的 Datalog 绝对不适合这种聚合;我的建议确实是使用 or-join 以发出零数量:
[:find ?account ?account-name (sum ?amount)
:with ?sum-term
:in $
:where [?account :account/name ?account-name]
(or-join [?account ?amount ?sum-term]
(and
[?sum-term :entry.record/account ?account]
[?sum-term :entry.record/amount ?amount])
(and
[(identity ?account) ?sum-term]
[(ground 0) ?amount]))]
另见:Datomic aggregations: counting related entities without losing results with zero-count
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。