简体   繁体   English

Postgres:获取计数并选择不同的

[英]Postgres: Get count & select distinct

I'm hitting a bit of a wall here with a pretty straightforward task (I think). 我在这里碰到了一个非常简单的任务(我认为)。

I have a table that looks something like this: 我有一张桌子,看起来像这样:

SELECT
        title, lat, lng, geocoder_identifier
    FROM entries
    WHERE geocoder_identifier IS NOT NULL;

条目表

If a user selects a place at the same lat/lng to another then the geocoder_identifier field is the same for both entries. 如果用户选择一个位置与另一个位置相同的纬度,则两个条目的geocoder_identifier字段相同。 What I need to do is group together any rows with the same geocoder_identifier, get a count of how many are in this group and then return the details for the first row in that group and discard the others. 我需要做的是使用相同的geocoder_identifier将任何行组合在一起,获取该组中有多少行的计数,然后返回该组中第一行的详细信息,并丢弃其他行。

The closest I've come to getting this done so far has been: 到目前为止,我最接近完成此操作的是:

SELECT DISTINCT
        (geocoder_identifier), title, lat, lng, entry_count
    FROM (
        SELECT
                title,description, lat, lng, geocoder_identifier, COUNT(*) OVER (PARTITION BY geocoder_identifier) AS entry_count
            FROM entries
            WHERE geocoder_identifier IS NOT NULL) AS e
    ORDER BY e.entry_count DESC;

This produces the following dataset for me: 这将为我生成以下数据集:

在此处输入图片说明

The problem here is that I cant really figure out how to make the results distinct by their geocoder_identifiers. 这里的问题是我无法真正弄清楚如何通过其geocoder_identifiers区分结果。

The simplest way would be: 最简单的方法是:

SELECT min(title), min(lat), min(lng), geocoder_identifier, count(*)
FROM entries
WHERE geocoder_identifier IS NOT NULL
group by geocoder_identifier
order by 5 desc

Note that this would return the smallest values for each of title, lat and lng for each given geocoder_identifier, not necessarily the first (although lat and lng should be the same throughout each geocoder_identifier) - it depends on how you want to determine the first title. 请注意,这将为每个给定的geocoder_identifier返回每个标题,lat和lng的最小值不一定返回第一个(尽管在整个geocoder_identifier中lat和lng应该相同)-这取决于您要如何确定第一个标题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM