我有一个名为weight
的表,字段为ID
,WEIGHT
,CREATED ON
。我在PHP变量中也有START
个日期和END
日期。现在我希望从开始日期到结束日期获得一周的明智记录
结果应该是这样的:
WEEK | WEIGHT | CREATED ON
-----+--------+-----------
1 | 50 | 2012-02-01
1 | 50 | 2012-02-03
1 | 50 | 2012-02-05
1 | 50 | 2012-02-07
2 | 50 | 2012-02-08
2 | 50 | 2012-02-10
2 | 50 | 2012-02-14
3 | 50 | 2012-02-15
3 | 50 | 2012-02-17
3 | 50 | 2012-02-17
如何实现它?
答案 0 :(得分:4)
希望有所帮助
SELECT ID, weigth, created_on, WEEK(created_on) week
FROM weight
WHERE created_on BETWEEN start_date AND end_date
ORDER BY week
答案 1 :(得分:1)
如果已经在PHP变量中存储了开始日期和结束日期,则可以使用MySQL BETWEEN
关键字对表执行SELECT
查询,因此(PHP代码):
$query = "SELECT FROM weight WHERE `created on` BETWEEN '" . $start_date . "' AND '" . $end_date . "'";
我在上面包含了字符串引号('),因为我假设您已将变量存储为格式化为日期时间的PHP字符串,即YYYY-MM-DD HH:MM:SS,使用{{1}格式:date()
。
进一步阅读:http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
答案 2 :(得分:1)
尝试这个...
SELECT WEEKDAY(CREATED_ON)AS weekdays,weight,CREATED_ON
FROM weight
WHERE CREATED_on BETWEEN start_date AND end_date
GROUP BY weekdays
答案 3 :(得分:1)
尝试以下
SELECT WEEKDAY(CREATED_ON) AS week, weight, created_on
FROM weight
WHERE CREATED_on BETWEEN start_date AND end_date
ORDER BY week
这可以给你你想要的......
SELECT (SELECT COUNT(*) FROM myTable u2
WHERE
u2.date > u1.date) + 1 AS week, date FROM myTable u1
WHERE date between start_date AND end_date
ORDER BY week
在下面的查询中,日期是我的日期。
SELECT (WEEK(date, 5) -
WEEK(DATE_SUB(date, INTERVAL DAYOFMONTH(date) - 1 DAY), 5) + 1) as week, date
FROM myTable
WHERE date BETWEEN start_date AND end_date
ORDER BY week
假设我有
myDate
+++++++++++++++++++++
2012-02-01 12:12:12
2012-02-01 12:12:12
2012-02-01 12:12:12
2012-02-03 12:12:12
2012-02-05 12:12:12
2012-02-07 12:12:12
2012-02-08 12:12:12
2012-02-08 12:12:12
2012-02-10 12:12:12
2012-02-14 12:12:12
2012-02-15 12:12:12
2012-02-17 12:12:12
2012-02-17 12:12:12
2012-03-01 12:12:12
2012-03-03 12:12:12
2012-03-05 12:12:12
2012-03-07 12:12:12
以下是我想要的。
week |myDate
+++++++++++++++++++++++++++
1 |2012-03-07 12:12:12
2 |2012-03-05 12:12:12
3 |2012-03-03 12:12:12
4 |2012-03-01 12:12:12
5 |2012-02-17 12:12:12
5 |2012-02-17 12:12:12
6 |2012-02-15 12:12:12
7 |2012-02-14 12:12:12
8 |2012-02-10 12:12:12
9 |2012-02-08 12:12:12
9 |2012-02-08 12:12:12
10 |2012-02-07 12:12:12
11 |2012-02-05 12:12:12
12 |2012-02-03 12:12:12
13 |2012-02-01 12:12:12
13 |2012-02-01 12:12:12
13 |2012-02-01 12:12:12
要获得更多信息,请参阅以下查询...
SELECT (SELECT COUNT(distinct u2.myDate) FROM myTable u2
WHERE
u2.myDate > u1.myDate) + 1 AS week, myDate FROM myTable u1
WHERE 1=1
ordeR BY week
在您的情况下,WHERE
子句将为WHERE myDate between startDate AND endDate
答案 4 :(得分:-1)
计算START日期和CREATED ON日期之间的差异(全天),除以7,然后加1 - 如下所示:
SELECT
DATEDIFF(CREATED_ON, START) / 7 + 1,
WEIGHT,
CREATED_ON
FROM
weight
ORDER BY
CREATED_ON