I have 2 tables that I want to merge. I want to print all the products with their corresponding total quantity and total amount.
This is what I have.
//Product Table
productID productName
1 A
2 B
3 C
//Order Record (This came from 2 tables that I have successfully merged)
orderID productID quantity amount
1 1 5 100
2 2 2 50
3 2 3 150
I want to do this
productID productName totalQuantity totalAmount
1 A 8 250
2 B 2 50
3 C 0 0
//instead of 0 for total Quantity and total Amount, it shows 2 and 50 respectively.
Here is my php code. It correctly outputs the the data for the first 2 rows (product A and B) but when it comes to the last row (product C), it copies the data for product B. Please tell me what's wrong in my code? Thank you in advance.
$products = $wpdb->get_results("SELECT * FROM wp_products");
foreach($products as $product){
$productID = $product->productID;
$productName = $product->productName;
$orders = $wpdb->get_results("SELECT a.productID, SUM(a.quantity) as totalQuantity, SUM(a.amount) as totalSales FROM a INNER JOIN b ON a.orderID = b.orderID GROUP BY productID");
if(is_null($orders)){
$totalQuantity = 0;
$totalSales = '0.00';
}
foreach($orders as $order){
$totalQuantity = $order->totalQuantity;
$totalSales = $order->totalSales;
}
$orderItem = array(
'productID' => $productID,
'productName' => $productName,
'totalQuantity' => $totalQuantity,
'totalSales' => $totalSales
);
$records[] = $orderItem;
}
Quick fix is (just add WHERE to your query):
$orders = $wpdb->get_results("SELECT
a.productID,
SUM(a.quantity) as totalQuantity,
SUM(a.amount) as totalSales
FROM a
INNER JOIN b
ON a.orderID = b.orderID
WHERE a.productID = $productID
GROUP BY productID");
But looking at your fragment, I believe you can simplify it (replace full fragment) to:
$records = $wpdb->get_results("SELECT
p.productID,
p.productName,
COALESCE(SUM(a.quantity),0) as totalQuantity,
COALESCE(SUM(a.amount),0) as totalSales
FROM wp_products p
LEFT JOIN a
GROUP BY p.productID");
I don't believe your query is correct.
I don't see the table names. Try changing it to:
FROM `tablename` AS a INNER JOIN `othertable` AS b
Swap out tablename and other table with the names for table a and b.
Related
I'm working with PHP and MySQL, and I need to SUM the total amount of products joining 3 tables:
order_products: (There are multiple order products with the same name but different amounts in the table)
order_id (int)
product_name (varchar)
product_amount (int)
orders:
order_id (int)
order_date (varchar)
order_status (varchar)
supplier:
product_name (varchar)
product_amount (int)
So, I want to show how many products I sold and status is shipped and how many I ordered from the supplier in one single row. Any of two examples below will help me to achieve my goal.
Like:
Product Name (sum order_products) (sum supplier) Order status
first product 300 2500 Shipped_Only
second product 50 400 Shipped_Only
third product 10 600 Shipped_Only
Product Name (sum order_products) (sum supplier) Order status
first product 2200 2500 Not_Shipped
second product 400 400 Not_Shipped
third product 590 600 Not_Shipped
Are there any examples or other help that I can get to do this?
Edit:
Sample Data goes like this
order_products:
order_id product_name product_amount
255 product 1 200
256 product 1 100
257 product 2 50
258 product 3 10
orders:
order_id order_date order_status
255 09.05.2018 Shipped
256 09.05.2018 Shipped
257 10.05.2018 Not_Shipped
258 10.05.2018 Not_Shipped
supplier:
product_name product_amount
product 1 2500
product 2 400
product 3 600
You should use a join on the aggregated subselect.
SELECT t1.product_name, t1.sum_order_products, t2.supplier_sum, t1.order_status
FROM (
SELECT op.product_name, SUM(op.product_amount) sum_order_products, o.order_status
FROM order_products op
INNER JOIN orders o ON op.order_id = o.order_id
WHERE o.order_status = 'Shipped'
GROUP BY op.product_name, o.order_status
) t1
LEFT JOIN (
SELECT s.product_name, SUM(s.product_amount) supplier_sum
FROM supplier s
GROUP BY s.product_name
) t2 ON t1.product_name = t2.product_name
ORDER BY t1.order_status, t1.product_name
From What I understand, I think this is what you want, please give more clarity if this is not what you are expecting.
You will need to use GROUP BY clause and them you will have to use count() function to count the number of rows for the results coming from Group By Clause. I am writing an example of how to use a group by clause, you will need to modify the query as per your need.
SELECT
order_products.product_name,
count(*) as Total_Orders,
MAX(supplier.product_amount) as Supplier_Amt,
orders.order_status
FROM supplier
INNER JOIN order_products ON supplier.product_name = order_products.product_name
INNER JOIN orders ON orders.order_id = order_products.order_id
WHERE orders.order_status = 'Not_Shipped'
GROUP BY order_products.product_name, orders.order_status;
You will need to queries, you can write the other one, just replace WHERE orders.order_status = 'Not_Shipped' with WHERE orders.order_status = 'Shipped' Also if you want all in a single query, simply remove the where clause.
I am trying to retrieve the minimum price of some models.
Each model belongs to a certain group which belongs to a product.
I have the following tables:
Product
model_id product_id price
1 1 100
2 1 120
3 1 100
4 1 200
5 1 250
10 1 20
11 1 50
12 1 50
Product Overview
model_id product_id group_id
1 1 A
2 1 A
3 1 A
4 1 A
5 1 A
10 1 B
11 1 B
12 1 B
Product Group Optional
group_id product_id
B 1
Some groups could be optional, which means price will be zero unless the member wants to choose otherwise.
So in the example above, I want to get the sum of minimum price from each group.
We have two groups, group A and group B.
Group A minimum price value is 100 (model_id 1 and 3)
Group B minimum price value is 20 (model_id 10) but because Group B is optional then that means minimum price value is 0.
Overall sum of min values: 100 (Group A) + 0 (Group B) = 100
My code so far:
SELECT po.group_id,
CASE WHEN
((SELECT COUNT(*) FROM product_group_optional pgo
WHERE po.group_id = group_id AND po.product_id = 1 AND po.product_id = product_id) >= 1)
THEN SUM(0)
ELSE SUM(p.price)
END AS sum_price
FROM product_overview po, product p
WHERE po.product_id = 1
AND po.model_id = p.model_id
AND p.price = (
SELECT MIN(p2.price)
FROM product p2, product_overview po2
WHERE po2.product_id = 1 AND po2.group_id = po.group_id
AND po2.model_id = p2.model_id
)
GROUP BY po.group_id
The output:
group_id sum_price
A 200
B 0
The problem is that I get 200 for Group A but it should be 100.
There are 2 models with min value 100, model 1 and 3. And I assume these are sum together = 100 + 100 = 200.
Issue a) But I want to just take the min value, no matter how many times this value exists.
Issue b) Also, I am trying to get the SUM of those two output SUM of Group A and Group B.
But I am not sure how to do it.
I want it to be done in this query.
Desired output
Sum of all groups
100
Can anyone lead me to the right direction please?
You can use the following query:
SELECT SUM(min_price)
FROM (
SELECT po.group_id,
MIN(CASE WHEN pgo.group_id IS NULL THEN price ELSE 0 END) AS min_price
FROM Product AS p
INNER JOIN Product_overview AS po
ON p.product_id = po.product_id AND p.model_id = po.model_id
LEFT JOIN Product_group_optional AS pgo ON po.group_id = pgo.group_id
GROUP BY po.group_id) AS t
I'm not sure that I understand the keys of your tables, and the problem as well.
There is few questions.
a) The answer should be 120?
b) If the Product has no price, the is price null?
c) If there is a Product in a group with null price and others with price, should it be counted as 0?
Here is how you could get the sum of the lower prices of each group, ignoring the product_group_optional for while:
SELECT t2.group_id, sum(t2.new_price)
FROM
(
SELECT t.group_id, t.new_price
FROM
(
SELECT po.group_id, if(ifnull(pgo.product_id, true), p.price, 0) as new_price
FROM product p, product_overview po
LEFT JOIN product_group_optional pgo ON po.group_id = pgo.group_id
WHERE p.model_id = po.model_id
ORDER by po.group_id, new_price
) t
GROUP BY t.group_id
) t2
I have a table name products with all product details and another whs_products with quantity details of the products for each warehouse.
i want select id, code and name from products table and sum of quantity where products.id = whs_products.product_id
I am trying this
$this->db->select("id, code, name");
$this->db->from("products");
$this->db->join('whs_products', 'products.id = whs_products.product_id');
$this->db->select("quantity");
I getting the list products that exists in whs_products not the sum. Some products are listed twice as they have 2 entries in whs_products.
I want list all the products once only where no quantity I want put 0 in quantity and where its is more than 1 in whs_products I want display sum of all the quantity
Help will be much appreciated!
Table Structure
Products
id, code, name, unit, price
whs_products
id, product_id, warehouse_id, quantity
I have whs table too for warehouse
id, name, address
I tried this Sir,
$this->db->select("products.id as productid, products.code, products.name, products.unit, products.cost, products.price, sum(whs_products.quantity) as 'totalQuantity'")
->from('products')
->join('whs_products', 'whs_products.product_id=products.id', 'left')
->group_by("products.id");
$this->db->get();
Every thing is fine. But the total number of products are calculated wrongly. I think system add 1 to total products, each time gets quantity from whs_products. For some products quantity is 2 or 3 time depending on each warehouse.
Any solutions for this. I am very thankful for your support.
Please try out the following query and comment.
SQLFIDDLE DEMO
Sample data:-
Products
PID PNAME
1 j
2 k
3 m
whs_Products
WID PID QUANTITY
11 2 300
11 2 200
14 2 500
11 1 300
15 3 100
14 3 800
Query to get total by pid in whs_products
select pid, wid, sum(quantity)
from whs_products
group by pid, wid
;
Results:
PID WID SUM(QUANTITY)
1 11 300
2 11 500
2 14 500
3 14 800
3 15 100
query using a variable to get user input for pid and by pid, wid
-- group by pid and wid
set #var:='2'
;
select a.pid, b.pname, a.wid, sum(a.quantity)
from whs_products a
join products b
on b.pid = a.pid
where a.pid = #var
group by a.pid, wid
;
Results:
PID PNAME WID SUM(A.QUANTITY)
2 k 11 500
2 k 14 500
final query to show quantity by user input pid only
Query:
-- by pid only
set #var:='2'
;
select a.pid, b.pname, sum(a.quantity)
from whs_products a
join products b
on b.pid = a.pid
where a.pid = #var
group by a.pid
;
Results:
PID PNAME SUM(A.QUANTITY)
2 k 1000
Since OP wants in CodeIgniter
Here is a headstart for you to try. At first I had the impression you already know the syntax of codeigniter and you are looking for SQL logic, so you could convert it into the desired format you need.
$this->db->select("a.pid, b.pname, count(a.quantity) as 'toalQuantity'");
$this->db->from('wsh_products a');
$this->db->join('products b', 'a.pid=b.pid', 'inner');
$this->db->group_by("a.pid");
$where = "a.pid = 2";
$this->db->get();
$query->results_array();
Or write a funciton :) :
function getQuantity($prodid = false)
{
$this->db->select(a.pid, b.pname, count(a.quantity) as 'toalQuantity');
$this->db->join('wsh_products a', 'a.pid=b.pid');
if ($prodid !== false)
$this->db->where('a.pid', $prodid);
$query = $this->db->get('products b');
if($query->result() == TRUE)
{
foreach($query->result_array() as $row)
{
$result[] = $row;
}
return $result;
}
}
Edit as OP requested for LEFT JOIN in comments
SQLFIDDLE
To show all products in Products table, do the following:
In select show pid from Products table.
Use from Products Left Join Whs_Products
Group by pid from Products table
I'm afraid i have written a query & confused myself in the process despite it being quite simple.
I have 2 mysql tables.
Table1 has ... orderID, productID, quantity
Table2 has ... orderID, status, time
I need to do a query that will do the following...
Output (1 per line)
productID - Quantity where status = 1 & time < $lastactive.
I tried doing a query of Table 2 to fetch productID and count Quantity but then if 2 different orderID's have the same productID then it doesnt total them. Any help greatly appreciated (name of tables/rows are accurante).
Example:
orderID 123, productID 2, quantity 4
orderID 123, productID 5, quantity 6
orderID 678, productID 2, quantity 5
would output:
2 9
5 6
You should be able to use something similar to this:
select t1.productId, Sum(t1.quantity) Total
from table1 t1
inner join table2 t2
on t1.orderid = t2.orderid
where t2.status = 1
and t2.time < $lastactive
group by t1.productid
I have set the PHP variable $accountnumber to be that of the user who is viewing their profile page. On the page, I have a block with the user's information populated from the database, and I have a list of all products that we have, and I want to put a check mark next to each one that the customer has by assigning a class to it.
Here are my tables:
products
id | name | url | weight
100 p1 p1.html 1
101 p2 p2.html 2
102 p3 p3.html 3
103 p4 p4.html 4
104 p5 p5.html 5
105 p6 p6.html 6
products_accounts
account_number | product_id
0000001 100
0000001 104
0000001 105
0000002 101
0000002 103
0000002 104
0000002 105
0000003 100
0000003 102
I tried a LEFT OUTER JOIN, but was not able to determine if the $accountnumber matched an account_number in the products_accounts table for a specific product_id. The only way that I was able to accomplish this was to add a WHERE statement like this:
WHERE products_acccounts.account_number = '$accountnumber'
It gave the proper class to the product, but only showed the product that they had instead of all.
Here's my code:
$sql ="
SELECT
products.id,
products.name,
products.url,
products_accounts.account_number
FROM
products
LEFT OUTER JOIN
products_accounts
ON
products.id = products_accounts.product_id
";
$sql .="
GROUP BY
products.id
ORDER BY
products.weight
";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo '<span class="'; if($row['account_number'] == '$accountnumber')
{ echo'product_yes">'; } else { echo 'product_no">'; }
echo '' . $row['name'] . '<br /></span>';
}
If a customer has all product except P2 and P5, it SHOULD display like this:
✓P1
P2
✓P3
✓P4
P5
✓P6
It's better to filter out rows using SQL than PHP, like below:
$sql ="
SELECT
p.id,
p.name,
p.url,
pa.account_number
FROM
products p
LEFT OUTER JOIN
products_accounts pa
ON
p.id = pa.product_id
AND
pa.account_number = ".mysql_real_escape_string($accountnumber)."
ORDER BY
p.weight
";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo '<span class="'; if(!is_null($row['account_number']))
{ echo'product_yes">'; } else { echo 'product_no">'; }
echo '' . $row['name'] . '<br /></span>';
}
$getproducts = mysql_query("
SELECT id, name, url
FROM products
ORDER BY weight ASC");
while ($rowproducts = mysql_fetch_assoc($getproducts)) {
$product_id = $rowproduct['id'];
$product_name = $rowproduct['name'];
$product_url = $rowproduct['url'];
$getuserhasproduct = mysql_query("
SELECT DISTINCT product_id
FROM products_accounts
WHERE account_number = $accountnumber
AND product_id = $product_id");
$user_has_product = mysql_num_rows($getuserhasproduct);
if($user_has_product){
$class = "checked";
}
echo "<span class='$class'><a href='$product_url'>$product_name</a></span>";
unset($class);
} // end loop
This might help with performance
$getproducts = mysql_query("SELECT id, name, url,
(SELECT DISTINCT product_id
FROM products_accounts
WHERE account_number = '$accountnumber'
AND product_id = products.id) AS product_count
FROM products
ORDER BY weight ASC");
while ($rowproducts = mysql_fetch_assoc($getproducts)) {
$product_id = $rowproduct['id'];
$product_name = $rowproduct['name'];
$product_url = $rowproduct['url'];
$product_count = $rowproduct['product_count'];
if($product_count > 0){
$class = "checked";
}
echo "<span class='$class'><a href='$product_url'>$product_name</a></span>";
unset($class);
} // end loop
SELECT
products.id,
products.name,
products.url,
products_accounts.account_number
FROM
products
LEFT OUTER JOIN
(SELECT * FROM products_accounts WHERE account_number = $account_number) as products
ON
products.id = products_accounts.product_id
WHERE
";
$sql .="
GROUP BY
products.id
ORDER BY
products.weight
";
i think this is your answer, you need to filter your join table before the join. please check the syntax as i am not that familiar with php.
You're trying to use GROUP BY in a context that doesn't make sense if you want to retrieve all of the records. The GROUP BY clause should only be used if you want to aggregate data (i.e. get the sum, average, etc. of a bunch of records).