我有一个简单的表格 -
--------------------------------------------------
| srcip | dstip | dstport
--------------------------------------------------
| X | A | 80
--------------------------------------------------
| X | A | 443
--------------------------------------------------
| X | B | 8080
--------------------------------------------------
我想要这样的输出 -
--------------------------------------------------
| srcip | dstip | count
--------------------------------------------------
| X | A | 2
--------------------------------------------------
| X | B | 1
--------------------------------------------------
我正在尝试使用COUNT(distinct dstport) OVER(PARTITION BY dstip,dstport) as count
在窗口函数中但出现错误 WINDOW definition is not supported
最佳答案
首先,当您编写问题时,该值始终为“1”(或者可能是NULL
)。该代码正在计算dstport
,并且您正在按该值进行分区。所以,只能有一个。
您可以使用两级窗口函数来完成此操作。这是一种方法:
select t.*,
sum( (seqnum = 1)::int ) as count_distinct
from (select . . . ,
row_number() over (partition by dstip order by dstport) as seqnum
from . . .
) t
关于sql - 如何在Postgresql的窗口函数中计数 "distinct"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48677356/