【问题标题】:How to "distinct" count in a window function in Postgresl?如何在 Postgresql 的窗口函数中“区分”计数?
【发布时间】:2018-02-08 04:05:27
【问题描述】:

我有一张简单的桌子 -

--------------------------------------------------
| 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

【问题讨论】:

标签: sql postgresql window-functions


【解决方案1】:

首先,正如您所写的问题,该值始终为“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

【讨论】:

  • 唯一使用窗口函数的答案
【解决方案2】:

最简单的方法是使用两列计数如下:

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

【讨论】:

    【解决方案3】:
    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;
    

    Demo

    【讨论】:

      猜你喜欢
      • 2014-04-26
      • 1970-01-01
      • 2018-12-08
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 2018-12-15
      • 1970-01-01
      相关资源
      最近更新 更多