如何计算某些列上的不同

问题描述 投票:-1回答:2

想要在SQL结果中添加一个计数列,以计算同一天的同一封电子邮件是否读取相同的reportID计数为1。

DB #Report:

Reportid Name Country Doc      ReadDate        Email
100      AA   HK      011abc   2017-12-01   [email protected]
100      BB   HK      011abc   2017-12-01   [email protected]
200      BB   HK      012abc   2017-12-20   [email protected]
200      BB   HK      012abc   2017-12-21   [email protected]
300      CC   HK      013abc   2017-12-22   [email protected]
300      CC   HK      013abc   2017-12-22   [email protected]
300      CC   HK      013abc   2017-12-22   [email protected]

Expected outcome:
    Reportid Name Country Doc      Date        Count
    100      AA   HK      012abc   2017-12-01  1
    200      BB   HK      012abc   2017-12-20  2
    300      CC   HK      012abc   2017-12-22  1

我的SQL如下所示,但未能计算出计算的预期结果。它生成DB中的所有行,并且每次运行计数= 1。

Select ReportId,Name,Country, Doc, Date, count(distinct concat(ReportId,Date,email))
from #Report
Group by Reportid,Name,Country, Doc, Date, email
sql
2个回答
0
投票

你可以试试这个。只需从group by中删除Date列。

Select ReportId,Name,Country, Doc, MIN(Date) Date, count(distinct concat(ReportId,Date,email))
from #Report
Group by Reportid,Name,Country, Doc, email

0
投票

试试这个,仅在ReportId上分组,发送电子邮件并添加readdate不是空条件。它将为您提供不同的ReportId,email,readdate,并将获取所有其他字段的最小值。

考虑到ReportId和电子邮件不是空字段。

Select ReportId, email, MIN(readdate), MIN(name), MIN(country), MIN(Doc), count(*) as Count
from Report
where readdate is not null 
Group by ReportId, email
© www.soinside.com 2019 - 2024. All rights reserved.