简体   繁体   中英

What I am missing in my sql command?

I've the following data in a database table called visitas to which I want to do a query, to ease things I'm giving it ordered DESC on the column visita .

idcliente    idcomercio    visita
----------------------------------------------
12393            2         2013 12 07 13:43:59
   10            2         2013 11 30 16:34:56
    8            2         2013 11 30 12:34:56
   12            2         2013 11 25 16:34:56
    6            2         2013 11 25 12:34:56
    2            2         2013 11 18 12:34:56
    4            2         2013 11 18 12:34:56
    6            2         2013 11 18 12:34:56
    2            2         2013 11 11 12:34:56

I want to get the tablet ordered by the time of latest visita and the how many visits has the client in that visit done, for this test table the result would be this one

idcliente     #visits
---------------------
12393          1
   10          1
    8          1
   12          1
    6          2
    2          2
    4          1

(Well, I know time is exactly the same for 3 visits so it might not exactly have to be the result int his order, anyway my problem isn't related to this.

I thin the following sql sentence should be working to achieve the above:

SELECT 
   idcliente,
   COUNT(idcliente) 
FROM 
   visitas 
WHERE 
   idcomercio = 2 
GROUP BY 
   idcliente 
ORDER BY 
   visita DESC

But this query returns this result:

idcliente     #visits
---------------------
12393            1
   10            1
    8            1
   12            1
    4            1
    6            2
    2            2

Which is obviously wrong as client with idcliente 6 has done its visit later than client with idcliente 4.

Can someone figure out what I could be missing? I've tried to input some other things but none of them seems to work.

SELECT idcliente,COUNT(idcliente) FROM visitas WHERE idcomercio=2 
  GROUP BY idcliente ORDER BY MAX(visita) DESC

Without the MAX its not defied which visita value is used for sorting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM