2017-09-18 77 views
0

我有一個表,ROTAS志願者:peewee複雜的查詢,如果

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

那麼,我做了一些研究,但無法使其工作。所以我採取了一種替代estrategy,並將其移入一個函數,只是計數字段數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使用。