我有一个表,它存储访问过某个产品的用户列表(带有访问日期)。我编写了下面的查询来获取在'2021-02-01'和'2021-02-26'之间访问产品B的用户列表。SELECT DISTINCT UserName,Country,ADate,Product FROM Report WHERE UserName != '-' and Product='B and (CAST(ADate AS DATE) BETWEEN @startdate AND @enddate '
则给出如下结果:
UserName Country ADate Product
-------- ------ -------- ---------
asson IN 2021-02-10 00:00:00.000 B
rajan US 2021-02-23 00:00:00.000 B
rajan US 2021-02-25 00:00:00.000 B
moody US 2021-02-14 00:00:00.000 B
rajon US 2021-02-01 00:00:00.000 B
lukman US 2021-02-10 00:00:00.000 B
由于用户rajan在2天内访问了产品,即使我添加了distinct,它也显示了rajan的2个条目。所以我修改了查询如下:SELECT DISTINCT UserName,Country,max(ADate),Product FROM Report WHERE UserName != '-' and Product='B' and (CAST(ADate AS DATE) BETWEEN @startdate AND @enddate group by Username,product
这个查询给出了所需的结果。但我现在面临的问题是,当我选择超过一个月的差距表(说2个月之间的数据),我错过了一些数据在输出。我认为这可能是由于MAX(ADate)
。谁能给一个好的建议来解决这个问题?
这将按月给出每个用户的最新访问日期
SELECT DISTINCT UserName,Country, month(ADate) as month, max(ADate),Product FROM Report WHERE UserName != '-' and Product='B' group by UserName, Country, month, Product