vendredi 20 mars 2020

Mysql Query Or Laravel Eloquent for Average of multiple column

Here two tables.

table1:Customer

+----+-------+-------------+--------+
| id | Ip_Id | Customer_Id | Class  |
+----+-------+-------------+--------+
| 1  | 100   | A           | First  |
| 2  | 100   | B           | First  |
| 3  | 100   | C           | First  |
| 4  | 101   | D           | First  |
| 5  | 101   | E           | First  |
| 6  | 100   | F           | Second |
+----+-------+-------------+--------+

table2:Customer_Usage

+-------+-------------+----------------+--------+------------+
| Ip_Id | Customer_Id | Customr _Usage | Amount | Date       |
+-------+-------------+----------------+--------+------------+
| 100   | A           | 10             | 100    | 21-02-2020 |
+-------+-------------+----------------+--------+------------+
| 100   | B           | 20             | 200    | 22-02-2020 |
+-------+-------------+----------------+--------+------------+
| 100   | A           | 30             | 500    | 23-03-2020 |
+-------+-------------+----------------+--------+------------+
| 100   | B           | 40             | 500    | 24-02-2020 |
+-------+-------------+----------------+--------+------------+

The condition is while enter a value for search Ip_Id, example for 100 it will give a result like below. make average of the values from the date. How to make a joint and calculate average two columns Avg _Usage,Avg_Amount for these two tables in Laravel using Mysql

Result:

+-------+-------------+------------+------------+
| Ip_Id | Customer_Id | Avg _Usage | Avg_Amount |
+-------+-------------+------------+------------+
| 100   | A           | 20         | 300        |
+-------+-------------+------------+------------+
| 100   | B           | 30         | 350        |
+-------+-------------+------------+------------+

Am using below query.

$results  = DB::table('Customer')
->select('Customer.Ip_Id','Customer.Customer_Id', 'Customer_Usage.Usage')
->where('Ip_Id', 100)                
->get();


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire