如何 "distinct" 在 Postgresql 中的 window 函数中计数?
How to "distinct" count in a window function in Postgresl?
我有一个简单的 table -
--------------------------------------------------
| srcip | dstip | dstport
--------------------------------------------------
| X | A | 80
--------------------------------------------------
| X | A | 443
--------------------------------------------------
| X | B | 8080
--------------------------------------------------
我想要这样的输出-
--------------------------------------------------
| srcip | dstip | count
--------------------------------------------------
| X | A | 2
--------------------------------------------------
| X | B | 1
--------------------------------------------------
我正在尝试在 window 函数中使用 COUNT(distinct dstport) OVER(PARTITION BY dstip,dstport) as count
但出现错误 WINDOW definition is not supported
首先,正如您所写的问题,该值始终为“1”(或者可能 NULL
)。代码正在计数 dstport
并且您正在按值进行分区。所以,只能有一个。
您可以使用两级 window 功能来完成此操作。这是一种方法:
select t.*,
sum( (seqnum = 1)::int ) as count_distinct
from (select . . . ,
row_number() over (partition by dstip order by dstport) as seqnum
from . . .
) t
with a as(
Select 'X' srcip,'A' dstip, 80 dstport
Union
Select 'X','A',443
Union
Select 'X','B',8080
)
select srcip,dstip,count(dstip) from a
group by srcip,dstip
order by dstip;
最简单的方法是使用两列计数,如下所示:
SELECT srcip , dstip , COUNT(dstip) FROM tbl GROUP BY srcip , dstip
我有一个简单的 table -
--------------------------------------------------
| srcip | dstip | dstport
--------------------------------------------------
| X | A | 80
--------------------------------------------------
| X | A | 443
--------------------------------------------------
| X | B | 8080
--------------------------------------------------
我想要这样的输出-
--------------------------------------------------
| srcip | dstip | count
--------------------------------------------------
| X | A | 2
--------------------------------------------------
| X | B | 1
--------------------------------------------------
我正在尝试在 window 函数中使用 COUNT(distinct dstport) OVER(PARTITION BY dstip,dstport) as count
但出现错误 WINDOW definition is not supported
首先,正如您所写的问题,该值始终为“1”(或者可能 NULL
)。代码正在计数 dstport
并且您正在按值进行分区。所以,只能有一个。
您可以使用两级 window 功能来完成此操作。这是一种方法:
select t.*,
sum( (seqnum = 1)::int ) as count_distinct
from (select . . . ,
row_number() over (partition by dstip order by dstport) as seqnum
from . . .
) t
with a as(
Select 'X' srcip,'A' dstip, 80 dstport
Union
Select 'X','A',443
Union
Select 'X','B',8080
)
select srcip,dstip,count(dstip) from a
group by srcip,dstip
order by dstip;
最简单的方法是使用两列计数,如下所示:
SELECT srcip , dstip , COUNT(dstip) FROM tbl GROUP BY srcip , dstip