选择计数和聚合,但只能是唯一的

时间:2014-04-22 05:09:44

标签: sql unique aggregate

我有一个数据库(MSSQL),其表格如下:

CREATE TABLE [dbo].[Ciphers](
    [Time] [datetime] NULL,
    [Hostname] [varchar](50) NULL,
    [ClientIP] [varchar](50) NULL,
    [UserAgent] [varchar](550) NULL,
    [CipherName] [varchar](200) NULL,
    [CipherVersion] [varchar](100) NULL,
    [CipherBits] [varchar](50) NULL
) ON [PRIMARY]

几行可能如下所示:

enter image description here

现在我想计算每个顶级域名的CipherName,CipherVersion和CipherBits组合的出现次数。

几乎是这样的:

SELECT CipherName, CipherVersion, CipherBits, COUNT(ClientIP) As "Hits" 
from Ciphers
WHERE Hostname like '%domain.com' 
Group by CipherName, CipherVersion, CipherBits 

关键是我只想计算每个客户端IP的唯一实例。也就是说,如果客户浏览过sub.domain.com和test.domain.com,我不想将其视为两个,只需一个。

2 个答案:

答案 0 :(得分:0)

鉴于您不是按HostName进行分组,看起来您只需要COUNT(DISTINCT x)

SELECT CipherName, CipherVersion, CipherBits, COUNT(DISTINCT ClientIP) As "Hits" 
from Ciphers
WHERE Hostname like '%domain.com' 
Group by CipherName, CipherVersion, CipherBits;

SqlFiddle here

答案 1 :(得分:0)

你可以试试这个 -

SELECT CipherName, CipherVersion, CipherBits, COUNT(DISTINCT ClientIP) OVER (PARTITION BY CipherName, CipherVersion, CipherBits) As "Hits" 
from Ciphers
WHERE Hostname like '%domain.com';