0

I have some problems with performing a query using Diesel library. I have table:

    create table tasks
(
    id         serial                                        not null
        constraint tasks_pkey
            primary key,
    name       varchar(128)                                  not null,
    rate       numeric(10, 2) default 0                      not null,
    time_spent numeric(10, 2)
);

Model:

#[derive(Debug, Serialize, Deserialize, Identifiable, Queryable)]
#[table_name="tasks"]
pub struct Task {
    pub id: i32,
    pub name: String,
    pub rate: BigDecimal,
    pub time_spent: Option<BigDecimal>
}

Schema:

table! {
    tasks (id) {
        id -> Int4,
        name -> Varchar,
        rate -> Numeric,
        time_spent -> Nullable<Numeric>,
    }
}

The target is that I need to get Sum of rate * time_spent. I meam total amount. Who can help me with that?

nocl1p
  • 111
  • 7
  • Can you expand on your question? Right now, it sounds like you simple need: `let total = task.rate * task.timespent.unwrap_or(BigDecimal::from_str(0).unwrap)`. How is your question related to diesel? Do you want the sum of all tasks in the database's `rate * timespent`? – Ibraheem Ahmed Nov 28 '20 at 00:27
  • I need to do this `select sum(t.total) from (select rate * time_spent as total from tasks) as t`. I use postgres db. – nocl1p Nov 28 '20 at 06:12
  • @nocl1p I dont think what you want is possible with diesel dsl.Seems like you need a raw query here. https://docs.diesel.rs/1.4.x/diesel/dsl/fn.sql_query.html – Njuguna Mureithi Nov 28 '20 at 07:00
  • @NjugunaMureithi, thanks. It works. – nocl1p Nov 28 '20 at 07:37

0 Answers0