我有这样的查询
CREATE FUNCTION getVisitChartByClient(date_from DATE, date_to DATE, statusname TEXT, club_uuid TEXT)
RETURNS TABLE(date date, entries bigint) AS $$
DECLARE
ids UUID[];
BEGIN
ids = string_to_array(club_uuid,',');
RETURN QUERY SELECT d.date, count(v.id) AS entries
FROM (SELECT i::date AS date
FROM generate_series(date_from, date_to, '1 day'::interval) i
) d
LEFT JOIN (
SELECT v.created_at, v.id FROM visit AS v
LEFT JOIN club AS c ON v.club_id= c.id
AND status = statusname
AND c.uuid = ANY(ids)
GROUP BY v.id
) AS v
ON d.date = v.created_at::date
GROUP BY d.date
Order By d.date ASC;
END;
$$ LANGUAGE plpgsql;
但有时我不想传递statusname或club id,我如何在查询中使用IF ELSE语句,或者如何创建查询然后执行?
答案 0 :(得分:2)
尝试:
AND status = coalesce(statusname,status)
和
AND case when club_uuid is null then then true else c.uuid = ANY(ids) end
这样:
RETURN QUERY SELECT d.date, count(v.id) AS entries
FROM (SELECT i::date AS date
FROM generate_series(date_from, date_to, '1 day'::interval) i
) d
LEFT JOIN (
SELECT v.created_at, v.id FROM visit AS v
LEFT JOIN club AS c ON v.club_id= c.id
AND status = coalesce(statusname,status)
AND case when club_uuid is null then then true else c.uuid = ANY(ids) end
GROUP BY v.id
) AS v
ON d.date = v.created_at::date
GROUP BY d.date
Order By d.date ASC;
当然你需要将NULL传递给函数而不是" normal"值