How to sort query results by journal date OR reference date?

The problem:

The solution:
2024-10-31 17.14.01

Setup

  1. Copy the code:
#+BEGIN_QUERY
{:title [:h3 "Smart sort by date"]
 :query [
  :find ?day (pull ?b [*])
  :where
    [?b :block/refs ?r]
    [?r :block/name "test"]
    [?b :block/page ?p]
    [?b :block/refs ?dr]
    (or
       [?p :block/journal-day ?day]
       (and
          [(missing? $ ?p :block/journal-day)]
          [?dr :block/journal-day ?day]
       )
     )
 ]
 :result-transform (fn [result]
   (->> result
     (partition 2)
     (sort-by (fn [[day obj]] day) )
     (map (fn [[day obj]]
       (update obj :block/properties (fn [u]
         (assoc u :day day)
       ))
     ))
   )
 )
 :remove-block-children? true
 :group-by-page? false
 :collapsed? false
}
#+END_QUERY
  1. Insert it to Logseq
  2. Change line [?r :block/name "test"]: replace "test" to any reference name you want.