我有一个查询
SELECT
cd.signoffdate,
min(cmp.dsignoff) as dsignoff
FROM clients AS c
LEFT JOIN campaigns AS cmp ORDER BY dsignoff;
如果我想在postgres查询中内置这样的内容,它会起作用,我该怎么做
如果cd.signoffdate
为空,则应将min(cmp.dsignoff) as dsignoff
作为值,然后按此列排序,换句话说,它应按dsignoff
和cd.signoffdate
顺序排列把它作为一个列,这是可能的,怎么样?
答案 0 :(得分:2)
您的查询可能如下所示:
SELECT c.client_id, COALESCE(c.signoffdate, min(cmp.dsignoff)) AS signoff
FROM clients c
LEFT JOIN campaigns cmp ON cmp.client_id = c.client_id -- join condition!
GROUP BY c.client_id, cd.signoffdate -- group by!
ORDER BY COALESCE(c.signoffdate, min(cmp.dsignoff));
或者,使用简化的语法:
SELECT c.client_id, COALESCE(c.signoffdate, min(cmp.dsignoff)) AS signoff
FROM clients c
LEFT JOIN campaigns cmp USING (client_id)
GROUP BY 1, cd.signoffdate
ORDER BY 2;
c
,但引用为cd
。GROUP BY
。clients
的主键列进行分组,并将其命名为client_id
。client_id
将两个表链接在一起。COALESCE()
在signoffdate
IS NULL。答案 1 :(得分:0)
ORDER BY coalesce(cd.signoffdate, min(cmp.dsignoff));
但是,您在原始查询中是否需要一些GROUP BY?
答案 2 :(得分:0)
您可以使用COALESCE
SELECT COALESCE(cd.signoffdate, min(cmp.dsignoff)) as dsignoff
我不确定你是否可以在Postgres中通过合并订购 - 可能值得按两列排序