gpt4 book ai didi

sql - 将 Postgres 查询结果合并到一个表中

转载 作者:行者123 更新时间:2023-11-29 12:40:33 26 4
gpt4 key购买 nike

我有两个有效的 Postgres 查询。

SELECT date_trunc('hour', time) t, COUNT(*) AS "SC15" FROM logfile
WHERE source = 'SC15' AND type = 'Sort'
GROUP BY t ORDER BY t;

SELECT date_trunc('hour', time) t, COUNT(*) AS "SC71" FROM logfile
WHERE source = 'SC71' AND type = 'Sort'
GROUP BY t ORDER BY t;

如何让结果在单独的列中并排显示?按小时分组的 t(间隔)列、SC15 列和 SC17 列。我试过 UNION 和 INTERSECT。我想我需要做一个临时表?不确定如何。谢谢!

最佳答案

没有必要在两个查询中这样做

SELECT 
date_trunc('hour', time) t,
COUNT(*) FILTER (WHERE source = 'SC15') AS "SC15",
COUNT(*) FILTER (WHERE source = 'SC71') AS "SC71"
FROM logfile
WHERE source IN ('SC15', 'SC71') AND type = 'Sort'
GROUP BY t
ORDER BY t

IN 运算符允许您过滤多个值。 FILTER 子句在计数之前过滤掉一些行。

关于sql - 将 Postgres 查询结果合并到一个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52631472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com