Dataview: display the sum of a table column

What I’m trying to do

I have a simple table, where one of the columns, labeled Score, is numeric.

The table code is here:

TABLE WITHOUT ID
file.link as Date,  
choice(Sleep, "✅", "❌") as 🛌,  
choice(Exercise, "✅", "❌") as 🏋‍♂,  
choice(Drawing, "✅", "❌") as 🎨,  
choice(Work, "✅", "❌") as 💻,
Sleep + Exercise + Drawing + Work as SCORE
FROM #dailies 
WHERE file.day <= date(now) AND file.day >= date(now) - dur(30days)  
SORT file.day ASC  

The table works fine.

What I want: a number, separate from the table, that shows the average SCORE of the table.

NOTE: I do not want this to be part of the table itself. I would love to simply have a paragraph element or something below and away from the table that displays just one number (the average SCORE).

Things I have tried

I’ve tried the solutions listed in the following links:

to no avail…

Given that your table actually shows the score you want to average, then the following table should produce the number you want:

```dataview
TABLE WITHOUT ID average(rows.score)
FROM #dailies 
FLATTEN Sleep + Exercise + Drawing + Work as score
WHERE file.day <= date(now) AND file.day >= date(now) - dur(30days)  
GROUP BY true
```

You could debug this by removing the GROUP BY true line, and just use TABLE WITHOUT ID score to verify that it’s showing the correct scores to average.

However this produces an entire table to present this one number, which is a bit excessive, so lets add some dataviewjs around this query to lift out just that one result:

```dataviewjs

const result = await dv.query(`
  TABLE WITHOUT ID average(rows.score)
  FROM #dailies 
  FLATTEN Sleep + Exercise + Drawing + Work as score
  WHERE file.day <= date(now) AND file.day >= date(now) - dur(30days)  
  GROUP BY true
`)

if ( result.successful ) {
  const average = result.value.values[0][0]  // First rows, first column
  dv.paragraph("The average score is " + average)
} else
  dv.paragraph("~~~~\n" + result.error + "\n~~~~")

Hope this helps, and actually works as it is untested… :smiley:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.