选择不同的ID

时间:2013-05-24 20:07:06

标签: mysql date unique

我们想要一个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"篇。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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