表结构以及记录:
+--------------+----------+---------------------+-----------+-------------+-----
--------+--------+---------+----------+--------+--------+----------+-------+
| chanceitemId | chanceId | contactTime         | linkmanId | contactKind | cont
actMode | userId | content | nextTime | chance | volume | saleTime | phase |
+--------------+----------+---------------------+-----------+-------------+-----
--------+--------+---------+----------+--------+--------+----------+-------+
|           66 |       26 | 2010-12-23 17:23:00 |         0 |         509 |
      0 |      0 | a2      | NULL     |      0 |   NULL | NULL     |     0 |
|           67 |       26 | 2010-12-07 17:23:00 |         0 |         509 |
      0 |      1 | a1      | NULL     |      0 |   NULL | NULL     |     0 |
|           73 |       27 | 2010-12-28 17:24:00 |         0 |         509 |
      0 |      0 | b1      | NULL     |     30 |    123 | NULL     |     0 |
|           74 |       27 | 2010-12-29 17:24:00 |         0 |         509 |
      0 |      0 | b2      | NULL     |      0 |   1234 | NULL     |     0 |
|           75 |       27 | 2010-12-30 17:25:00 |         0 |         509 |
      0 |      3 | b3      | NULL     |      0 |   NULL | NULL     |     0 |
+--------------+----------+---------------------+-----------+-------------+-----
--------+--------+---------+----------+--------+--------+----------+-------+目的,查该表中,各个chanceId对应的最近一次contactTime的记录以及该chanceId对应的chanceitem记录数。
使用了以下的sql:
select chanceitemId,count(chanceitemId) as cnt,chanceId,contactTime,content,nextTime,chance,volume, saleTime from t_cust_chanceitem group by chanceId having contactTime in (select Max(contactTime) from t_cust_chanceitem GROUP by CHANCEID);但是得不到chanceId=27的记录值,请问该如何写这句sql?

解决方案 »

  1.   

    select chanceitemId,count(*),chanceId,contactTime,content,nextTime,chance,volume, saleTime 
    from (
    select *
    from t_cust_chanceitem
    Order By contactTime DESC
    ) t
    group by chanceId
      

  2.   

    原来的语句根本不对。你需要了解
    select chanceitemId,count(chanceitemId) as cnt,chanceId,contactTime,content,nextTime,chance,volume, saleTime from t_cust_chanceitem group by chanceId
    的结果是什么?
    然后再执行 having contactTime in (select Max(contactTime) from t_cust_chanceitem GROUP by CHANCEID);判断。