用于计算非唯一字段

时间:2015-04-27 08:54:34

标签: sql-server count group-by unique

我试图弄清楚如何在查询中的电子邮件字段中添加计数,但我遇到的问题是所需的一些数据是唯一的ID, DateTime,但电子邮件是不是我想要的数量。我只是无法弄清楚如何在一个SQL行中完成它。

e.g。返回: -

101, bla, prd, test@test.com, alfred, comp, test, 2015-10-10 10:10:10, 2  <-- count
100, bla, prd, test@test.com, alfred, comp, test, 2015-09-10 10:11:10, 2
099, bla, prd, anoter@email.com, simpson, comp, test, 2014-10-10 10:10:10, 1
098, bla, prd, bla@email.com, henry, comp, test, 2014-05-10 10:10:10, 1

查询

select TOP 200 
    ID, 
    FromPage, 
    Product, 
    Email, 
    Name, 
    Company, 
    Industry, 
    DateTime, 
    (count code here as EmailTotal)
from InstallEmails
WHERE product like 'prd%' 
ORDER BY ID DESC

2 个答案:

答案 0 :(得分:0)

如果您使用的是SQL Server 2005或更高版本,则可以使用window function

SELECT  TOP 200 
        ID, 
        FromPage, 
        Product, 
        Email,
        Name, 
        Company, 
        Industry, 
        DateTime, 
        EmailTotal = COUNT(*) OVER(PARTITION BY Email)
FROM    InstallEmails
WHERE   product like 'prd%' 
ORDER BY ID DESC;

对于早期版本,您需要使用子查询:

SELECT  TOP 200 
        ID, 
        FromPage, 
        Product, 
        Email,
        Name, 
        Company, 
        Industry, 
        DateTime, 
        EmailTotal = (  SELECT  COUNT(*) 
                        FROM    (   SELECT  TOP 200 Email
                                    FROM    InstallEmails
                                    WHERE   product like 'prd%' 
                                    ORDER BY id DESC
                                ) AS ie2
                        WHERE   ie2.Email = ie.Email
                    )
FROM    InstallEmails AS ie
WHERE   product like 'prd%' 
ORDER BY ID DESC;

答案 1 :(得分:0)

解决了..似乎没问题。

select TOP 200 *,  (select COUNT(email) from InstallEmails where email = t.email) as EmailTotal
from InstallEmails as t
where product like 'prd%' 
ORDER BY ID DESC