Mysql:Group by,order,max的组合。获取分组集的最大值并应用条件

时间:2012-11-05 09:16:32

标签: mysql cakephp cakephp-2.0

以下格式在mysql数据库中有一个表保留。

id | customer_id | user_id | date_booked
1  | 1           | 1       | 2012-11-5

我想获得特定用户的客户数量。所以我写了查询

select count(*), user_id, customer_id,date_booked from reservations where user_id=1 group by customer_id

以期望的方式获取结果。但是date_booked,我得到了第一个记录的值。即,如果ID为2的客户有4条记录,则获取第一条记录的date_booked值。我想要最新的价值,所以我改进了下面的查询

select count(*), user_id, customer_id,max(date_booked) from reservations where user_id=1 group by customer_id

这会记录最高日期。这仍然不是我想要获取的结果集。我想要最新的日期,但应该小于当前日期(今天)。

有没有办法写这样的条件

max(date_booked)<date(now())

我想获取最大日期但不到今天。我想在CakePHP中实现这一点。如果有人可以帮助查询我可以写它cakePHP格式。

如有必要,请改进问题。

3 个答案:

答案 0 :(得分:1)

试试这个:

select count(*), user_id, customer_id,max(date_booked) 
from reservations 
where user_id=1 
and date_booked<date(now())
group by customer_id

答案 1 :(得分:1)

select count(*), 
       rs.user_id, 
       rs.customer_id,
       CASE WHEN max(rs.date_booked)<date(now()) then max(rs.date_booked) 
           else (select max(r.date_booked) from reservations r where r.user_id=rs.user_id 
                  and r.date_booked<date(now()) and r.customer_id=rs.customer_id
                  ) end as latestdate
from reservations rs 
where rs.user_id=1 
group by rs.customer_id

答案 2 :(得分:1)

select  count(*),a.user_id,a.customer_id,
   IF(max(a.date_booked)>now(), b.date_booked, max(a.date_booked)) as date_booked
from reservations a left join 
   (select max(date_booked) as date_booked,customer_id 
        from reservations where date_booked < now() group by customer_id) b
on a.customer_id=b.customer_id
where a.user_id=1 
group by customer_id