Django中具有分组的多个聚合

时间:2019-01-05 18:44:20

标签: sql django postgresql orm aggregation

我正在尝试制作一个仪表板,并且必须使用django ORM而不是原始查询,但是我找不到适合该SQL查询的等效项:

SELECT * FROM (
    SELECT persons.name, 
        SUM(CASE WHEN work_hours.work_type='A' THEN work_hours.count ELSE 0 END) as additional_hours , 
        SUM(CASE WHEN work_hours.work_type='D' THEN work_hours.count ELSE 0 END) as duty_hours, 
        CASE WHEN SUM(CASE WHEN work_hours.stat_type='D' THEN work_hours.count ELSE 0 END) > 0 THEN 
            1.0*SUM(CASE WHEN work_hours.work_type='A' THEN work_hours.count ELSE 0 END)/
                SUM(CASE WHEN work_hours.work_type='D' THEN work_hours.count ELSE 0 END) 
        ELSE -1 END as over_rate 
    FROM daily_work_hours as work_hours 
    inner join personnel as persons 
    on work_hours.person_id = persons.id 
    GROUP BY persons.name 
    order by over_rate desc) stats
WHERE duty_hours>100;

有人可以帮我吗?

0 个答案:

没有答案