visit
mysql表:
+---------+-------------+------------+--------+---------------------+
| visitId | visitSiteId | homeSiteId | userId | time |
+---------+-------------+------------+--------+---------------------+
| 1 | 1 | 1 | 1001 | 2013-09-01 11:50:12 |
| 2 | 1 | 1 | 1001 | 2013-09-03 12:50:12 |
| 3 | 2 | 1 | 1001 | 2013-09-04 13:50:12 |
| 4 | 2 | 1 | 1001 | 2013-09-07 11:00:00 |
| 5 | 2 | 1 | 1001 | 2013-09-09 12:32:12 |
| 6 | 2 | 1 | 1001 | 2013-09-13 15:48:12 |
| 7 | 2 | 2 | 1002 | 2013-09-01 11:00:12 |
| 8 | 2 | 2 | 1002 | 2013-09-02 12:50:12 |
| 9 | 2 | 2 | 1002 | 2013-09-05 13:50:12 |
| 10 | 1 | 2 | 1002 | 2013-09-06 11:50:12 |
| 11 | 1 | 2 | 1002 | 2013-09-07 12:50:12 |
| 12 | 2 | 2 | 1002 | 2013-09-15 13:50:12 |
+---------+-------------+------------+--------+---------------------+
记录访问日期时间、访问的站点和用户主站点
我想找到如何从上述数据中输出 3 个报告。
- 返回所有非主页访问次数 >= 主页访问次数的用户;任何日期
- 返回任何具有非家庭站点访问计数 >= 输入的最小整数的用户,例如非家庭访问次数 >= 10
- 1 和 2 的日期范围即时间 >= '2013-09-01 11:50:12' AND Time <= '2013-09-13 15:48:12'
我对 MySQL 非常陌生,并且在使用子查询语法时遇到了困难,因此将不胜感激: The Queries below will return the counts of Home Visits and Non Home Visits but I can get my head around Subquery for combined result
SELECT COUNT(v.user_id), v.user_id FROM visit v WHERE v.Site <> v.HomeSite GROUP BY v.user_id;
SELECT COUNT(v.user_id), v.user_id FROM visit v WHERE v.Site = v.HomeSite GROUP BY v.user_id;
SELECT COUNT(v.user_id), v.user_id FROM visit v WHERE v.Site <> v.HomeSite AND v.Time >= '2013-09-01 11:50:12' AND v.Time <= '2013-09-13 15:48:12' GROUP BY v.user_id;
SELECT COUNT(v.user_id), v.user_id FROM visit v WHERE v.Site = v.HomeSite AND v.Time >= '2013-09-01 11:50:12' AND v.Time <= '2013-09-13 15:48:12' GROUP BY v.user_id;
这是帮助测试的 MySQL 创建表和插入数据:
CREATE TABLE `dbName`.`visit`(`visitId` INT(11) NOT NULL AUTO_INCREMENT, `visitSiteId` INT(11), `homeSiteId` INT(11), `userId` INT(11), `time` DATETIME, PRIMARY KEY (`visitId`));
INSERT INTO `dbName`.`visit`(`visitSiteId`,`homeSiteId`,`userId`,`time`) VALUES
(1,1,1001,'2013-09-01 11:50:12'),
(1,1,1001,'2013-09-03 12:50:12'),
(2,1,1001,'2013-09-04 13:50:12'),
(2,1,1001,'2013-09-07 11:00:00'),
(2,1,1001,'2013-09-09 12:32:12'),
(2,1,1001,'2013-09-13 15:48:12'),
(2,1,1002,'2013-09-01 11:00:12'),
(2,1,1002,'2013-09-02 12:50:12'),
(2,1,1002,'2013-09-05 13:50:12'),
(1,1,1002,'2013-09-06 11:50:12'),
(1,1,1002,'2013-09-07 12:50:12'),
(2,1,1002,'2013-09-15 13:50:12');