Help with sort-by after group-by

Hello logseq community,

i found this query somewhere on github/gist and i wanted to add a final sort-by at the end of the query.

I failed after trying to learn advanced queries. The query creates a table with pages and counts the TODOs on each page. In a final step i want to sort the output by page(name).

How would i do that?

#+BEGIN_QUERY 
{ :title "TODO by page"
:query [
:find (pull ?b [
  :block/marker 
  :block/parent 
  { :block/page [ :db/id :block/name] }
])
:where [?b :block/marker "TODO" ]
]

:result-transform 
(fn [result] 
    (map (fn [[key value]] {
      :page (get key :block/name) 
      :count (count value)
   }) 
   (group-by 
      :block/page result)
   )
)

:view (fn [rows] [:table 
[:thead [:tr [:th "Page"] [:th "Count"] ] ] 
[:tbody 
(for [r rows] [:tr 
[:td [:a {:href (str "#/page/" (get r :page))} (get r :page)] ] 
[:td (get r :count)] ])
]] ) }
#+END_QUERY

Welcome.

  • The final step is the outer one.
  • Therefore, should wrap the result with the sort-by.
  • Try adjusting the :result-transform section like this:
    :result-transform
    (fn [result]
      (sort-by :page
        (map (fn [[key value]] {
          :page (get key :block/name)
          :count (count value)
        })
        (group-by
          :block/page result)
        )
      )
    )
    
1 Like

Yes, that did the trick. Thank you.

How can i reverse the sort order (descending)?

(EDIT: I added my question back, because you were so quick in answering).

  • The easy way is to wrap (sort-by ...) with (reverse ...)
  • The intermediate way is to replace sort-by :page with sort-by :page >
  • The advanced way is to use compare inside sort
2 Likes