Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two tables with group by condition

Here i want to join two table and want to produce the output like

Akbar Travels building      2018-10
Thrikandiyur Quarters       2018-10


Akbar Travels building     2018-11
Thrikandiyur Quarters      2018-11

Here i have two tables name table A,table B,table A structure looks like this

category_id              category_name  
    5               Akbar Travels building          
    6               Thrikandiyur Quarters 

table B structure looks like this

id     paying_month     parent_category     
1         2018-10           5   
2         2018-10           5   
3         2018-11           5   
4         2018-11           5   
5         2018-10           6   

Here for getting output i wrote my code code like this

public function get_date_wise_pdf_report($from, $to)
{
       $query=$this->db->query("SELECT * from tableA A left join tableB B  on A.category_id = B.parent_category and B.paying_month BETWEEN '{$from}' AND '{$to}' ");
       return $query->result();
 }

but when i use this am getting like this

Akbar Travels building     2018-10
Akbar Travels building     2018-10
Akbar Travels building     2018-11
Akbar Travels building     2018-11
Thrikandiyur Quarters      2018-10

Am unable to give group by statement here and if i gave only two rows will be the out come,please help me to solve

like image 789
user_777 Avatar asked Oct 02 '18 10:10

user_777


People also ask

Can we apply GROUP BY clause while joining two tables?

Using Group By with Inner Join SQL Inner Join permits us to use Group by clause along with aggregate functions to group the result set by one or more columns. Group by works conventionally with Inner Join on the final result returned after joining two or more tables.

Can we use GROUP BY and join together?

GROUP BY With JOIN Example In the above example, JOIN and GROUP BY both clauses used together in a single query. After joining both tables(Employee and Department), joined table grouped by Department name.

How do you GROUP BY based on conditions?

Conditions in the HAVING clause are applied after groups are formed. The search condition of the HAVING clause examines the grouped rows and produces a row for each group where the search condition in the HAVING clause is true.

How do you join a table conditionally?

A conditional column join is a fancy way to let us join to a single column and to two (or more) columns in a single query. We can accomplish this by using a case statement in the on clause of our join. A case statement allows us to test multiple conditions (like an if/else if/else) to produce a single value.


1 Answers

Use distinct

SELECT distinct A.category_name,B.paying_month
from tableA A left join tableB B  on A.category_id = B.parent_category and 
B.paying_month BETWEEN '{$from}' AND '{$to}'
order by B.paying_month
like image 127
Fahmi Avatar answered Oct 01 '22 14:10

Fahmi