簡體   English   中英

如何在Postgresl的窗口函數中“區分”計數?

[英]How to “distinct” count in a window function in Postgresl?

我有一張簡單的桌子-

--------------------------------------------------
| 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窗口函數中的COUNT(distinct dstport) OVER(PARTITION BY dstip,dstport) as count ,但是WINDOW definition is not supported錯誤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
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;

演示版

最簡單的方法是將count與兩列一起使用如下:

SELECT srcip , dstip , COUNT(dstip) FROM tbl GROUP BY srcip , dstip 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM