我为志愿者提供了ROTA桌子:
dater | vol1id | vol2id | vol3id | vol4id
-----------+------------+-----------+----------+-----------
2017-08-01 | 1 | 13 | 14 | 33
2017-08-02 | 32 | 150 | 3 | 4
其中一个旧查询会检查当天已经有多少志愿者,因此它会在HTML表格中显示,颜色取决于可用性。这样做是这样的:
SELECT
(CASE WHEN vol1id IS NULL THEN 0 ELSE 1 END) +
(CASE WHEN vol2id IS NULL THEN 0 ELSE 1 END) +
(CASE WHEN vol3id IS NULL THEN 0 ELSE 1 END) +
(CASE WHEN vol4id IS NULL THEN 0 ELSE 1 END)
FROM rotas
WHERE (dater BETWEEN '2017-08-01' AND '2017-08-31')
ORDER BY dater;
我想将这个SQL查询转换为peewee过滤,是否可以用peewee完成?
答案 0 :(得分:1)
嗯,我做了一些研究,但无法使其发挥作用。所以我选择了另一种策略,并将其移动到一个函数中,只计算字段数NOT NULL。
CREATE OR REPLACE FUNCTION count_volunteers(start_date date, end_date date)
RETURNS TABLE (day date, volunteer_count bigint) AS
$func$
SELECT
dater,
(SELECT COUNT(*)
FROM (values (T.vol1id), (T.vol2id), (T.vol3id), (T.vol4id)) AS v(col)
WHERE v.col IS NOT NULL)
FROM rotas as T
WHERE (dater BETWEEN start_date AND end_date)
ORDER BY dater;
$func$
LANGUAGE sql;
现在要容易得多,因为它现在只是以这种方式添加查询:
SELECT day, volunteer_count FROM count_volunteers('2017-08-01', '2017-08-31');
peewee现在可以很容易地使用它。