Yii2 : how to use distinct , groupby , sum and where conditions - php

I want execute below query in using Yii2 syntax selection query,
select distinct pfs_id, unitprice, sum(qty)
from order_items
where order_id= id
and item_farm_id = id
group By pfs_id
I tried several times but still not getting luck,
Please any one help.

Below query return you desire result as array.
$data=ModelName::find() //replace your model name here
->select('distinct(pfs_id),unitprice,sum(qty)')
->where(['order_id'=>id,'item_farm_id'=>id])
->groupBy('pfs_id')
->asArray->all();
You can also use alias:
$data=ModelName::find()
->select('distinct(pfs_id) as pfs_id,unitprice,sum(qty) as sum_of_qty')
->where(['order_id'=>id,'item_farm_id'=>id])
->groupBy('pfs_id')
->asArray->all();

Related

Count function in mysql

There are 2 table called employee and approvedcadre.I want to get count of raws where
employee.Des_name=approvedcadre.Des_name
AND employee.service=approvedcadre.service
AND employee.Grade=approvedcadre.Grade
AND employee.SalaryCode=approvedcadre.SalaryCode
WHERE app_category='permanent'"
FROM approvedcadre
WHERE Ins_name='$InsName'
I herewith attached the current code.but I don't know how to apply "SELECT * FROM approvedcadre WHERE Ins_name='$InsName' to the query?
[Above mentioned code]
try this code it for count the rows
in php use * and use mysqli_num_rows
SELECT COUNT(*)
FROM approvedcadre
JOIN employee ON employee.Des_name=approvedcadre.Des_name
AND employee.service=approvedcadre.service
AND employee.Grade=approvedcadre.Grade
AND employee.SalaryCode=approvedcadre.SalaryCode
WHERE approvedcadre.Ins_name='$InsName' and approvedcadre.app_category='permanent'"

Laravel : Select and GroupBy SQL Query Error. Multiple Selects with groupBy? Is it Possible?

I have an 2 tables Ratings and Attributes , i pass the month and get all record of both users and count this , i have already count this record , and divided into groups by user_id , But in my attribute table i have a user name , and join this table to get attribute name , My query is that
$months = \Request::get('month');
$records = DB::table("ratings")
->select(DB::raw("SUM(ratings.attribute_score) as score"))
->whereRaw('MONTH(ratings.created_at) = '.$months)
->join('users','ratings.user_id','=','users.id')
->groupBy('ratings.user_id')
->get();
dd($records);
And get json like that
But i want to get name of the specific user with score but here multiple selects not working in this query how to use multiple select to get attributes table records? if i am using this query. Thanks Developers in advance
->select(DB::raw("SUM(ratings.attribute_score) as score , ratings.user_id , attributes.attributes_name"))
Using this the select not working here it always return the score Jason like show in the Sceenshot. How can i do to selects multiples using groupBy??
USE THIS TO GET USERNAME WITH SCORE COUNTS. Try This
$months = \Request::get('month');
$records = DB::table("ratings")
->select(DB::raw('SUM(ratings.attribute_score) as score, users.name as
user_name'))
->whereRaw('MONTH(ratings.created_at) = '.$months)
->join('users','ratings.user_id','=','users.id')
->groupBy('users.name')
->get();
return view('attribute.show' , compact('records'));

MySQL JOIN pass PHP variable to two tables

I have the following MySQL query in PHP that passes a variable to complete the query:
SELECT * from mobile_tech WHERE uid=$uid order by timestamp DESC limit 0,1
I have the following MySQL JOIN that provides data from two tables:
SELECT mobile_tech.latitude, mobile_tech.longitude, mobile_tech.timestamp, mobile_tech.uid, gbl_qemplisting.EmpNo, gbl_qemplisting.FirstName, gbl_qemplisting.LastName
FROM mobile_tech, gbl_qemplisting
WHERE mobile_tech.uid=gbl_qemplisting.EmpNo AND date(timestamp)='$currentday'
group by uid
I need to combine these two queries into one with a JOIN and still passing the $uid variable to complete the query.
I've tried the following and it did not work:
SELECT mobile_tech.latitude, mobile_tech.longitude, mobile_tech.timestamp, mobile_tech.uid, gbl_qemplisting.EmpNo, gbl_qemplisting.FirstName, gbl_qemplisting.LastName
FROM mobile_tech, gbl_qemplisting
WHERE mobile_tech.uid=$uid AND gbl_qemplisting.EmpNo=$uid AND date(timestamp)='$currentday'
Your query will return a cross product between the mobile_tech and gbl_emplisting rows for $uid. If you just want one row, as in the first query, use ORDER BY and LIMIT similarly.
SELECT mobile_tech.latitude, mobile_tech.longitude, mobile_tech.timestamp, mobile_tech.uid, gbl_qemplisting.EmpNo, gbl_qemplisting.FirstName, gbl_qemplisting.LastName
FROM mobile_tech, gbl_qemplisting
WHERE mobile_tech.uid=$uid AND gbl_qemplisting.EmpNo=$uid AND date(timestamp)='$currentday'
ORDER BY mobile_tech.timestamp
LIMIT 1
Please try with this and say the result
SELECT mobile_tech.latitude,
mobile_tech.longitude,
mobile_tech.timestamp,
mobile_tech.uid,
gbl_qemplisting.EmpNo,
gbl_qemplisting.FirstName,
gbl_qemplisting.LastName
FROM mobile_tech inner join gbl_qemplisting
on mobile_tech.uid=gbl_qemplisting.EmpNo
where mobile_tech.uid=$uid AND date(timestamp)='$currentday'

How to count if value of a variable is repeated?

I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}

Codeigniter active record left join issue

I have two tables 'accounts_transactions' and 'accounts_bills_transactions'.
I have to left join these two using active record of codeigniter.But the names of key columns used to join are different.So I am not getting the key column from the left table in the output .What query should I write to get the key column from the left table included in the result.
My code is
$this->db->select('*');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_bills_transactions.transaction_id','left');
$query = $this->db->get();
So, as you see the key columns used to join here are , id from left table and transaction_id from second table.The problem is that I am not getting the id from left table in the result.But I am getting all other columns.I assume the problem is because of difference in column names used to join.ie both the column names are not named 'id' .So how can I get the id from left table included in the result.
You could alias them:
$this->db->select('accounts_transatctions.*, account_transactions.id AS a_id,
accounts_bills_transactions.*,
account_bills_transactions.id AS ab_id');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_transactions.transaction_id','left');
$query = $this->db->get();
The two IDs will now be available as a_id and ab_id (or whatever alias you choose)
Note: I'm not sure if you can alias in AR without avoiding escaping (haven't been using CI for a while). Should you get any error for that reason, just pass false as second parameter of $this->db->select():
$this->db->select('...', false);
you can try this if you confuse of using $this->where or $this->join
$query = $this->db->query("select ......");
return $query;
You problem is so simple. You can use this query
$query = $this->db
->select('at.*')
->select('abt.id as abt_id');
->from('accounts_transactions at');
->join('accounts_bills_transactions abt', 'at.id = abt.transaction_id','left');
->get()
->result();
When same column are used in join it selects only one. You need to give alise to the other column in second table. The best practice is to use a structure like this
accounts_transatctions
--------------------------
accounts_transatctions_id
other_columns
accounts_bills_transactions
---------------------------
accounts_bills_transactions_id
accounts_transatctions_id
other_columns

Categories