如何在Postgres中实现Oracle计数(不同)分区

时间:2017-04-19 21:32:02

标签: sql oracle postgresql

这是我在select语句中的sql示例。从oracle转换为postgres,需要一种简单的方法来重新实现oracle count在postgres中的分区。

int StringList::remove(string value)
{
    Node* curr = head;
    while (curr != NULL)
    {
        if ((curr->data) == value)
        {
            if (curr == head)
            {
                head = curr->next;
                if (head->prev != NULL)
                    head->prev = NULL;
                else
                    tail = NULL;
                delete curr;
                curr = head;
            }
            else if (curr == tail)
            {
                tail = curr->prev;
                tail->next = NULL;
                delete curr;
                curr = NULL;
            }
            else
            {
                curr->prev->next = curr->next;
                curr->next->prev = curr->prev;
                Node* next = curr->next;
                delete curr;
                curr = next;
            }
        }
        else
            curr = curr->next;
    }
}

1 个答案:

答案 0 :(得分:0)

Postgres不直接支持count(distinct)。但您可以使用子查询来实现它:

select . . .,
       sum( (seqnum_tm = 1)::int) as mob_segments_count ,
       sum( (seqnum_tr = 1)::int) as countries_count
from (select . . .,
             row_number() over (partition by pm.trans_id, pm.country_reg_region_cd order by pm.country_reg_region_cd) as seqnum_tr,
             row_number() over (partition by pm.trans_id, pm.mobseg_state order by pm.pm.mobseg_state) as seqnum_tm
      . . .
     ) . . .

这个想法很简单。计算row_number()键和不同列上的partition by。然后,只需加上值为“1”的次数。这需要子查询,因为您无法嵌套窗口函数。