0

我正在使用 PostgreSQL 和 bookshelf 并尝试运行一个简单的 SQL 查询,以便在单个查询中获得多个计数。此查询如下所示:

SELECT SUM(CASE WHEN date_last_check > (now() - interval '1 MONTH') THEN 1 ELSE 0 END) as since_two_months,
       SUM(CASE WHEN date_last_check > (now() - interval '7 DAY') THEN 1 ELSE 0 END) as since_one_week,
       SUM(CASE WHEN date_last_check > (now() - interval '1 DAY') THEN 1 ELSE 0 END) as since_one_days
FROM myTable;

在书架CASE的函数中做语句似乎是不可能的。sum()我试过了:

return myTable.query(function(qb:any){
  qb.sum("(CASE WHEN date_last_check > (now() - interval '1 MONTH') THEN 1 ELSE 0 END) as since_two_months")
})

这将返回以下查询:

select sum("(SUM(CASE WHEN date_last_check > (now() - interval '1 MONTH') THEN 1 ELSE 0 END)") as "since_two_months" from "myTable"

由于 ) 后的引号,这不起作用sum("

有谁知道如何在不使用原始查询的情况下完成这项工作?

4

2 回答 2

0

我找到了一个糟糕的解决方案,它是在书架查询中使用 known raw: return myTable.query(function(qb:any){ qb.select(bookshelf.knex.raw("SUM(CASE WHEN date_last_check > (now() -间隔 '1 MONTH') THEN 1 ELSE 0 END) as since_one_month")); })

于 2022-02-21T15:13:52.983 回答
0

而是使用现代语法进行条件聚合:聚合FILTER子句:

SELECT count(*) FILTER (WHERE date_last_check > now() - interval '1 month') AS since_two_months  -- one_month?
     , count(*) FILTER (WHERE date_last_check > now() - interval '7 days')  AS since_one_week
     , count(*) FILTER (WHERE date_last_check > now() - interval '1 day')   AS since_one_day
FROM   mytable;

看:

于 2022-02-21T15:37:00.587 回答