我有一个名为activity
的表,它使用以下列:
LoginDate, LoginID, Department, IsMGR
我尝试了这个查询:
SELECT COUNT(*),
DATE_FORMAT( LoginDate, '%m%d%Y' ) AS LogDate,
LoginID, Department
FROM `activity`
WHERE IsMGR = '1'
AND LoginDate > '2011-01-01 00:00:00'
GROUP BY LoginID, LogDate
ORDER BY LoginID,LogDate DESC
我最终得到的是:
3 02172011 sdavis accounting 1 02162011 sdavis accounting 2 02132011 sdavis accounting 1 02102011 sdavis accounting 5 02092011 sdavis accounting 4 02082011 sdavis accounting 1 03182011 dmorris marketing 1 03092011 dmorris marketing 6 04142011 cchan technology 1 03282011 cchan technology 2 03262011 cchan technology 2 03112011 cchan technology 1 03102011 cchan technology
这是计算他们登录的每一天的次数。我想要的是每天只计算一次,并且每个人的所有日期都计算在一起他们登录的日子,以及最后一天。使用上面的数据样本,我想要的输出应该是
6 02172011 sdavis accounting 2 03182011 dmorris marketing 5 04142011 cchan technology
所以我想要的是以某种方式将上述分组结果按第二组标准分组......?
答案 0 :(得分:5)
试试这个:
SELECT COUNT(distinct LoginDate) AS NumLogins,
DATE_FORMAT( MAX(LoginDate), '%m%d%Y' ) AS LastLogDate,
LoginID, Department
FROM activity
WHERE IsMGR='1' AND LoginDate > '2011-01-01 00:00:00'
GROUP BY LoginID, Department
ORDER BY LoginID, Department DESC
答案 1 :(得分:1)
select
count(distinct LoginDate) as loginCount,
max(LoginDate) as lastLoginDate,
LoginID,
Department
FROM `activity`
where IsMGR='1'
and LoginDate > '2011-01-01 00:00:00'
GROUP BY LoginID, Department
ORDER BY LoginID, lastLoginDate DESC