You will need group by
to get the counters you need. You also need to apply the aggregate function to H.Date
, otherwise it is not clear which date to choose:
SELECT P.ID, P.Name, COUNT(H.P_ID) as Count, MAX(H.Date) as LastDate FROM P LEFT JOIN H ON P.ID=H.P_ID GROUP BY P.ID, P.Name ORDER BY Count DESC
I chose MAX(H.Date)
to create the date of last consumption; if you need another date from H
, change the aggregation function.
I'm not sure if sqlite allows sorting by alias; if it is not, replace
ORDER BY Count DESC
with
ORDER BY COUNT(H.P_ID) DESC
source share