将Postgres查询结果合并到一张表中

时间:2018-10-03 16:13:53

标签: sql postgresql

我有两个有效的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。我想我需要做一个临时表?不确定如何。谢谢!

2 个答案:

答案 0 :(得分:2)

两个查询中无需这样做

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子句在计数之前会过滤掉一些行。

答案 1 :(得分:1)

您可以将CTE与窗口功能row_number()一起使用,并在加入结果之后。请注意,最好使用left join,因为CTE中的行数可能不同

with l1 as (
SELECT
  row_number() over(order by t) rn,
  date_trunc('hour', time) t,
  COUNT(*) c
FROM logfile l1
WHERE source = 'SC15' AND type = 'Sort'
GROUP BY t
ORDER BY t
),
l2 as (
SELECT 
  row_number() over(order by t) rn,
  date_trunc('hour', time) t, 
  COUNT(*) c
FROM logfile
WHERE source = 'SC71' AND type = 'Sort'
GROUP BY t
ORDER BY t
) SELECT l1.t, l1.c, l2.t, l2.c
FROM l1
LEFT JOIN l2 on l1.rn=l2.rn

作为另一种变体,您可以尝试类似的操作

select 
date_trunc('hour', time) t,
count(*) over (partition by date_trunc('hour', time), source, type) c
from logfile
where source in ('SC15', 'SC71') AND type = 'Sort'