ruby-on-rails 从联接表返回具有多个COUNT的表

c3frrgcw  于 2022-11-19  发布在  Ruby
关注(0)|答案(1)|浏览(124)

我有两张table:ClientDocument
一个client有多个documents
| 委托方|
| - -|
| 标识符|
| 姓名|
| 文件|
| - -|
| 标识符|
| 姓名|
| 到期日期|
| 客户端ID|

到期日期格式为YYYY-MM-DD

我想返回这样一个表:
| 标识符|姓名|文档计数|过期的|30天|
| - -|- -|- -|- -|- -|
| 一个|客户端A| 10个|五个|2个|
| 2个|客户端B|八个|八个|第0页|
| 三个|客户端C|十三|第0页|10个|
现在我的代码是这样的:

Client.all.left_joins(:documents).group(:id).select('clients.*, COUNT(documents.id) AS documents_count')

我错过了最后两列。
如何获得这两列?
我试探着:

Client.all.left_joins(:documents).group(:id).select("clients.*, COUNT(documents.id) AS documents_count, COUNT(documents.expiration < #{Date.today}) AS expired")

但是过期的列返回布尔值而不是数字。
| 标识符|姓名|文档计数|过期的|
| - -|- -|- -|- -|
| 一个|客户端A| 10个|真的|
| 2个|客户端B|八个|真的|
| 三个|客户端C|十三|真的|

r55awzrz

r55awzrz1#

设置.

BEGIN;
CREATE TABLE client (
    id bigint,
    name text
);
CREATE TABLE document (
    id bigint,
    name text,
    expiration_date date,
    client_id int
);
INSERT INTO client
SELECT
    i,
    'client_' || i
FROM
    generate_series(1, 5) _ (i);
INSERT INTO document (id, name)
SELECT
    i,
    'document' || i
FROM
    generate_series(1, 5) _ (i),
    generate_series(1, 3, 1);
COMMIT;

UPDATE
    document
SET
    client_id = (4 * random())::int + 1;

UPDATE
    document
SET
    expiration_date = (date '2022-10-25' + (random() * 30)::int);

查询

SELECT DISTINCT
    c.id,
    c.name,
    count(expiration_date) FILTER (WHERE expiration_date > CURRENT_DATE -30) OVER (PARTITION BY d.id) AS count_last_month,
    count(expiration_date) FILTER (WHERE expiration_date > CURRENT_DATE) OVER (PARTITION BY d.id) AS count_expire
FROM
    client c
    LEFT JOIN document d ON d.id = c.id
ORDER BY
    c.id;

或者简单的一个。

SELECT
    c.id,
    c.name,
    count(expiration_date) FILTER (WHERE expiration_date > CURRENT_DATE -30) AS count_last_month,
    count(expiration_date) FILTER (WHERE expiration_date > CURRENT_DATE) AS count_expire
FROM
    client c
    LEFT JOIN document d ON d.id = c.id
GROUP BY
    1,
    2
ORDER BY
    c.id;

我不知道ruby,但从this发布,我认为你可以运行纯sql查询。

相关问题