I have three tables
post
id | statement | date
features
id | feature
post_feature (many to many table between Post and Feature)
post_id | feature_id
I want to fire a query that will give me count of different distinct features and its respective features for the posts that are in given date period. I have just started learning SQL and I am not able to crack this one.
I tried the following one but not getting correct results.
 SELECT f.feature, count(f.feature)
   FROM  post_feature l 
   JOIN  features f ON (l.featureid = f.id AND l.featureid IN (
   select post.id from post where post.date > 'some_date'))
   GROUP BY f.feature
                You can count multiple COUNT() for multiple conditions in a single query using GROUP BY. SELECT yourColumnName,COUNT(*) from yourTableName group by yourColumnName; To understand the above syntax, let us first create a table.
SQL – count() with Group By clause The count() function is an aggregate function use to find the count of the rows that satisfy the fixed conditions. The count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.
You can GROUP BY multiple columns, to get the count of each combination.
COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.
You can try like this:
       SELECT f.feature, count(f.feature)
       FROM  post_feature l 
       JOIN  features f ON l.featureid = f.id 
       JOIN  post p ON l.post_id =p.id 
       WHERE p.date > 'some_date'
       GROUP BY f.feature
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With