Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite COUNT and LEFT JOIN - how to combine?

Tags:

sql

sqlite

There are two tables: one (P) that contains list of products, the other one (H) contains history of products consumed. Every product can be consumed 0 or more times. I need to build a query that will return all products from P along with number of times every product has been consumed, sorted by the times it's been consumed. Here is what I did:

SELECT P.ID, P.Name, H.Date, COUNT(H.P_ID) as Count 
FROM P 
LEFT JOIN H 
  ON P.ID=H.P_ID  
ORDER BY Count DESC

This seems to work only if history table contains data, but if it does not - the result is incorrect. What am I doing wrong?

like image 311
Asahi Avatar asked May 01 '13 19:05

Asahi


People also ask

How do I join two tables and counts in SQL?

To achieve this for multiple tables, use the UNION ALL. select sum(variableName. aliasName) from ( select count(*) as yourAliasName from yourTableName1 UNION ALL select count(*) as yourAliasName from yourTableName2 ) yourVariableName; Let us implement the above syntax.

How join multiple tables with LEFT join?

Syntax For Left Join:SELECT column names FROM table1 LEFT JOIN table2 ON table1. matching_column = table2. matching_column; Note: For example, if you have a left table with 10 rows, you are guaranteed to have at least 10 rows after applying join operation on two tables.

Does SQLite have left join?

Introduction to SQLite LEFT JOIN clause Similar to the INNER JOIN clause, the LEFT JOIN clause is an optional clause of the SELECT statement. You use the LEFT JOIN clause to query data from multiple related tables.


1 Answers

You need a group by to get the counts that you need. You also need to apply an aggregate function to H.Date, otherwise it is not clear which date to pick:

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 picked MAX(H.Date) to produce the date of last consumption; if you need a different date from H, change the aggregating function.

I am not sure if sqlite lets you sort by alias; if it does not, replace

ORDER BY Count DESC

with

ORDER BY COUNT(H.P_ID) DESC
like image 68
Sergey Kalinichenko Avatar answered Nov 14 '22 23:11

Sergey Kalinichenko