【发布时间】:2015-02-14 13:38:08
【问题描述】:
我有 2 个带日期的表格,采用时间戳格式, 我要数一数每周总共有多少条记录...
...只需一个查询即可获得结果...
所以我会用例子更好地解释它:
2表,第一个:
table name: visitor
ID | time | ref (now i put in fake timestamp in time column sorry)
--------------------
1 | 3455 | john
2 | 3566 | ted (week 40)
3 | 8353 | ted (week 38)
4 | 6673 | katy
5 | 6365 | ted (week 40)
6 | 4444 | john
7 | 3555 | ted (week 40)
和第二个(非常相似):
table name: users
ID | time | ref (now i put in fake timestamp in time column sorry)
--------------------
1 | 3455 | ted (week 41)
2 | 3566 | ted (week 42)
3 | 8353 | ted (week 40)
4 | 6673 | katy
5 | 6365 | ted (week 41)
6 | 4444 | john
7 | 3555 | ted (week 38)
8 | 6789 | ted (week 43)
我做这个查询,我得到这个结果:
SELECT WEEK(FROM_UNIXTIME(time)) AS week, COUNT( * ) AS tot
FROM visitor WHERE ref='ted' GROUP BY week
表格结果#1
week | tot
----------
38 | 1
40 | 3
43 | 1
我为第二张桌子做了一些:
SELECT WEEK(FROM_UNIXTIME(time)) AS week, COUNT( * ) AS totuser
FROM users WHERE ref='ted' GROUP BY week
表格结果#2
week | totuser
----------
38 | 1
40 | 1
41 | 2
42 | 1
但我只需要一个查询就可以得到这个结果:
week | tot | totusers
---------------------- (when both are 0 doent appear -like 39 for example-)
38 | 1 | 1
40 | 3 | 1
41 | 0 | 2
42 | 0 | 1
43 | 1 | 0
我知道我必须使用 LEFT JOIN、GROUP BY 和 IFNULL,但我总是做错事,我无法弄清楚。
按周顺序排列
感谢您的帮助。
【问题讨论】: