我正在学习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分配值。
发布于 2021-06-14 13:00:03
Datomic的Datalog肯定对这种聚合感到不舒服;我的建议确实是使用或-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
https://stackoverflow.com/questions/67962571
复制相似问题