0

我们想要一个 SQL 语句,列出唯一 IP/唯一 ID 对在任何唯一日期访问的次数,按唯一 ID/IP 对访问的最大次数排序。

这是表结构:

Column             Type
------------------------------
Date               Timestamp
NumberofUsers      smallint
ipaddress          varchar(16)
location           varchar(2)
Count              bigint(20)

这是我们一直在尝试的sql:

SELECT
  LicenseID, 
  MAX(Date) AS LatestAccess,
  COUNT(DISTINCT Location) AS DifferentCountries,
  COUNT(DISTINCT IPAddress) AS DistinctIPCount,
  COUNT(DISTINCT Date,IPAddress) AS DistinctDate
FROM
  LicenseHistory 
WHERE
  (LicenseID<>30002)
GROUP BY
  LicenseID 
ORDER BY
  DistinctDate DESC

以下是表格中 CSV 格式的一些示例日期:

2009-10-08 10:37,30002,8,24.108.64.80,CA,2399
2009-05-27 16:57,24508,50,24.108.64.80,CA,645
2008-11-06 12:04,30,100,24.108.64.80,CA,282
2008-02-04 10:51,24508,30,24.69.19.207,CA,62
2009-10-08 14:52,13136,5,24.108.64.80,CA,285
2013-05-13 13:10,718,10,66.251.68.106,US,23860
2008-02-12 11:10,30002,8,24.69.19.207,CA,36
2008-04-09 17:49,18504,10,70.90.32.57,US,121
2007-07-26 13:38,30002,8,76.226.201.191,US,2
2009-12-03 22:35,30002,8,196.25.255.214,ZA,14
2013-05-13 6:49,20341,4,66.232.201.125,US,2676
2007-07-28 23:57,30002,8,75.81.107.238,US,1
2007-07-29 10:39,30002,8,70.63.54.162,US,1
2007-07-30 3:53,30002,8,121.210.199.31,AU,4
2007-07-30 5:11,30002,8,41.207.67.10,KE,2

这是一些示例结果(尚不正确,最后一列不应与倒数第二个匹配):

uniqueID  LatestAccess         DifferentCountries  DistinctIPCount  DistinctDate
--------------------------------------------------------------------------------
20677     2013-05-13 18:20:15  4                   162              162
27749     2013-05-14 05:30:59  7                   155              155
459       2013-05-13 11:12:47  2                   143              143
24965     2013-05-14 13:44:56  6                   123              123
25226     2013-05-06 16:11:56  3                   104              104
20370     2013-05-14 05:54:04  4                   100              100

我认为问题出在"COUNT(DISTINCT Date,IPAddress) AS DistinctDate"作品中。

4

2 回答 2

1

你需要一个COUNT DISTINCT. 这是一个猜测,因为没有提供表结构:

SELECT
  VisitDate,
  COUNT(DISTINCT IPAddress, UniqueID) AS UniqueVisits
FROM MyTable
GROUP BY VisitDate
ORDER BY UniqueVisits DESC

或者,如果您visit date是日期时间或时间戳,请使用DATE函数删除时间部分(注意第二行和第五行的更改):

SELECT
  DATE(VisitDate),
  COUNT(DISTINCT IPAddress, UniqueID) AS UniqueVisits
FROM MyTable
GROUP BY DATE(VisitDate)
ORDER BY UniqueVisits DESC
于 2013-05-24T20:15:52.277 回答
0

您的日期格式中有时间。所以,我认为所有的日期都是独一无二的。尝试这个:

SELECT
  LicenseID, 
  MAX(Date) AS LatestAccess,
  COUNT(DISTINCT Location) AS DifferentCountries,
  COUNT(DISTINCT IPAddress) AS DistinctIPCount,
  COUNT(DISTINCT date(Date), IPAddress) AS DistinctDate
FROM
  LicenseHistory 
WHERE
  (LicenseID<>30002)
GROUP BY
  LicenseID 
ORDER BY
  DistinctDate DESC
于 2013-05-24T21:54:47.383 回答