How can i get count of number of rows that have boolean value true(or 1) in Room persistent database without using SELECT query?

前端 未结 2 1957
别跟我提以往
别跟我提以往 2021-02-13 01:45

I am working with Room persistent database in my project. I have a table in which there is a column for Boolean values as in 0 or 1, now i want the count of all Boolean values w

相关标签:
2条回答
  • 2021-02-13 02:29

    Using aggregate function sum may help you:

    select
        sum(
            case
                when t.VALUE = 1 then
                    1
                else
                    0
            end
        )
    from
        table t
    

    Please note, SQLite engine will read entire table, if no indexed by aggregating field. It's no problem if there only few records in the table, otherwise it's better to consider using from keyword of indexed fields.

    0 讨论(0)
  • 2021-02-13 02:30

    Finally I got the perfect solution! Just add this method in the DAO class as follows:

    @Query("SELECT COUNT(is_checked) FROM table WHERE is_checked = 1")
    int getNumberOfRows();
    

    All thanks to Florina Muntenescu at https://medium.com/@florina.muntenescu

    0 讨论(0)
提交回复
热议问题