postgresql - 用于 postgres 查询的子查询 count()

标签 postgresql gis aggregate-functions postgis

我有两个包含网络流量的表格,我正在加入并在 map 上进行可视化。

我正在尝试编写一个计数器来创建查询结果,其中包含特定 IP 地址在日志中出现的次数。我认为这将采用子查询的形式,返回主查询选择的特定行的行数。

当我运行以下查询时,我得到的错误是用作表达式的子查询返回的多于一行

select
squarespace_ip_addresses.ip,
squarespace_ip_addresses.latitude,
squarespace_ip_addresses.longitude,
st_SetSrid(ST_MAKEPOINT(squarespace_ip_addresses.longitude, squarespace_ip_addresses.latitude), 4326) as geom,
(select count(hostname) from squarespace_logs group by hostname) as counter,
squarespace_logs.referrer
from
squarespace_ip_addresses
left outer join
squarespace_logs
on
squarespace_ip_addresses.ip = squarespace_logs.hostname

有人向我建议的是选择中的子查询,该子查询按主查询输出过滤,对每一行运行该查询。

有没有人有任何见解?

最佳答案

聚合派生表中的数据(FROM 子句中的子查询):

select
    a.ip,
    a.latitude,
    a.longitude,
    st_SetSrid(ST_MAKEPOINT(a.longitude, a.latitude), 4326) as geom,    
    c.count,
    l.referrer
from squarespace_ip_addresses a
left join squarespace_logs l on a.ip = l.hostname
left join (
    select hostname, count(*)
    from squarespace_logs
    group by hostname
    ) c on a.ip = c.hostname

关于postgresql - 用于 postgres 查询的子查询 count(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53662604/

相关文章:

node.js - Postgres 尝试返回我的模型中不存在的列

postgresql - 由于 hstore,表上的 pg_restore 失败

python - 在 Rasterio 中 - 当仿射对象是单独的时,如何平铺表示地理引用图像的数组?

python - 有条件的 numpy.cumsum?

mysql - SQL 'WHERE' 基于SUM的限制

sql - 1 个 SQLITE 查询中的多个 COUNT

php - pg_prepare : cannot insert multiple commands into a prepared statement

sql - 窗口函数调用需要 OVER 子句

r - 如何在R或ArcGIS中处理多边形shapefile中的“孤立孔”?

Mysql join and sum 是加倍的结果