Home>
I want to achieve

I want to output the total of integer values ​​held by each User
There are the following DBs. (Item is integer)

<User id: 1, name: "guest1", item: 4>
<User id: 2, name: "guest2", item: 7>
<User id: 3, name: "guest3", item: 3>
..
..


How should I output the total of the item values ​​of Uesr.all on the Controller side?

  • Answer # 1

    If you add them allUser.sum (: item)

    When you want to narrow down by limitUser.limit (10) .sum (: item)I want to
    SELECT SUM (users..item) FROMusersLIMIT 10
    And you will get the total of all.

    So, do as follows.
    User.limit (10) .pluck (: item) .sum

    Or

    users = User.limit (10)
    User.from (users) .sum (: item)


    SELECT SUM (item) FROM (SELECTusers. * FROMusersLIMIT 10) subquery