Postgres条件下的变量

时间:2018-09-28 21:20:21

标签: sql postgresql

我希望能够在条件语句中包含二进制变量:

select sum(t.hours), count(tk.id) from time t
inner join tickets tk on tk.id = t.ticket_id
where tk.active = :active_type
and t.billable = :billable;

:active类型可以是'R''P'
:billable可以是TrueFalse

我为每个排列写了四遍,但这确实很丑。 Postgres是否允许某些东西使其更优雅?

1 个答案:

答案 0 :(得分:0)

您可以使用GROUP BY在单个查询中获得结果:

SELECT active, billable, SUM(t.hours), COUNT(tk.id)
FROM time t
INNER JOIN tickets tk ON tk.id = t.ticket_id
WHERE tk.active IN ('P', 'R')
GROUP BY active, billable
ORDER BY active, billable;

如果tickets.active只能是'R''P',则可以跳过WHERE子句。