Ok so I am a lil confused how to go about this and seek some help..
I have a mysql db that has a column named quantity and another called price_paid
what I want to do is take and add up the entire column of price_paid but to also take into account a quantity higher than 1.
Ex..
_____________ ______________
| quantity | | price_paid |
-------------- ---------------
1 2.99
2 9.99
1 1.99
How would I create the php / mysql to make that = a total of 24.96 ?
So far I am able to get the total of price_paid but what I have doesn't take into account the quantity column and it's value.
$comic_totals = "SELECT sum(price_paid) AS value_sum FROM `comic_db`.`comic_db`";
$total_db = mysqli_query($comic_connect, $comic_totals);
if(!total_db){
echo "Failed";
}
$tot_array = mysqli_fetch_assoc($total_db);
$sum = $tot_array['value_sum'];
echo "$".$sum;
so how do I turn that into what I need? Thanks
Let MySQL take care of multiplying the price by the quantity...
SELECT SUM(quantity * price_paid) AS value_sum
If you want quantity higher than 1 then add where clause
Like this
SELCET SUM(quantity * price_paid) as value
FROM comic_db.comic_db
WHERE quantity > 1;
Related
I have a table that stores price of products in that is hierarchically organized from country level to store level.
create table price_list(
product_id number,
country_id number,
region_id number,
store_id number,
price number
)
I need to search this table to generate invoice. The input for the function (not elaborated here) is in this pattern (i'll use json structure to explain):
{
header : {country_id:5, region_id:234, store_id:345},
items : {
0:{product_id:1001, quantity:5},
1:{product_id:299, quantity:1}
//, etc...
}
}
I want to get the price for the products specific to that store's setup.
Of course if every field is filled, I can search the price by using the complete select syntax.
select price from price_list where product_id = ? and country_id = ? and region_id = ? and store_id = ?
But there are cases where the fields in the table are incomplete, for example only the country_id and product_id is filled because the price is the same for that product in all regions and stores in that country. Let's say I don't want to populate all data with complete fields because of non-technical reasons. A sample data in the table is shown below.
product_id country_id region_id store_id price
1001 3 93 112 15
1001 3 93 113 15.5
1001 4 179 14
1001 4 185 13
1001 5 20
1001 5 999 999 25
Let's take an example if I want to execute this request
{
header : {country_id:5, region_id:300, store_id:500},
items : {
0:{product_id:1001, quantity:5},
}
}
This query will not return a result because country 5 does not specify specific price for each region and store except for region 999 store 999.
select price from price_list where product_id = 1001 and country_id = 5 and region_id = 300 and store_id = 500
Because no row is returned, I need to generalize the search, I start with using all fields, reducing one by one if no price is found.
where product_id = 1001 and country_id = 5 and region_id = 300
But still, this will not return any row. Then I generalized more, and this search gets the value.
where product_id = 1001 and country_id = 5
My current solution is exhaustive. Is there a better way to do this efficiently? The environment is Oracle 11g on php 5.4 and CodeIgniter2.
Why not create a variable which holds the where clause:
$priceWhereclause = "";
$params = [];
if(isset($productIdValue)){
$priceWhereclause .= "product_id = ? ";
$params[] = $productIdValue;
}
if(isset($countryIdValue)){
$priceWhereclause .= "and country_id= ? ";
$params[] = $countryIdValue;
}
Your query would look like:
select price from price_list where $priceWhereclause
put the $params in the execute($params) function.
I am using MySQL and have a table called sales. Its primary key is sales_id.
-------------------------------------
sales_id | invoice_id |
-------------------------------------
1 | 147
2 | 148
3 | 150
For sales_id 3 the invoice_id is supposed to be 149. I want to know which numbers are missing from invoice_id. I start invoice_id at 147 and end invoice_id at 4497. The invoice_id had no relation with sales_id.
Is it possible to know which numbers are missing from invoice_id, using a query?
I presume that you have a table of invoice - INVOICES. You may try:
SELECT invoice_id FROM INVOICES invoice
WHERE NOT EXISTS (SELECT * FROM SALES s WHERE invoice.invoice_id = s.invoice_id)
EDIT: If you don't have the INVOICES table, you may need to take all the invoices out before checking if there's any gap.
SELECT DISTINCT invoice_id FROM SALES ORDER BY invoice_id ASC
SELECT MAX(invoice_id) FROM SALES
then, by php:
for ($i = 1; $i < $max_invoice_id; $i++)
{
if (!in_array($i, $all_invoice_id))
{
$gapId[] = $i;
}
}
If you're just trying to find numbers out of the sequence in the example you've provided you could use something like this:
SELECT *
FROM `sales`
WHERE (
`invoice_id` - 147 - `sales_id`
) = 0
If you can provide a bigger sample set we might be able to tool a better answer for you.
set #suggest_invoice:=147;
select
sales_id,
invoice_id,
#suggest_invoice:=#suggest_invoice+1,
if(invoice_id=#suggest_invoice, 0, 1) as missing_invoice
from sales
order by sales_id;
I guess you almost getting all the records except the first two with missing_invoice=1
As you are searching for invoice_id then make sure you have an index on that column. otherwise queries will be slow.
You can try the following code
$inv_ids=range(147,4497);
$str_inv_ids=implode(",",$inv_ids);
$query="SELECT DISTINCT invoice_id FROM sales WHERE invoice_id IN ($str_inv_ids)";
$result=mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$inv_ids_db[]=$row['invoice_id'];
}
// It gives invoice Ids that are in $inv_ids but not in $inv_ids_db
$missing= array_diff($inv_ids,$inv_ids_db);
print_r($missing);
You can find gaps in a MySQL sequence using this query:
SELECT invoice_id+1
FROM sales s
WHERE NOT EXISTS (
SELECT NULL
FROM sales t
WHERE s.invoice_id = t.invoice_id+1
)
HAVING `invoice_id+1` < (SELECT MAX(invoice_id) FROM sales)
ORDER BY invoice_id
This will return all invoice_id missing from the sequence, regardless of sales_id.
I am attempting to create an end-user page where I present different servers that are available to check-out. A server at any given time can have either an "Available" status or a "Reserved" status. I'm using a MySQL backend. This is how I am doing my query:
SELECT *, COUNT(CASE WHEN Status = 'Available' THEN 1 ELSE NULL END) AS Amount
FROM products GROUP BY id
This is the result I get:
id,Server_Type,Status,Amount
1,BL460,Available,1
2,BL460,Available,1
3,BL460,Reserved,0
4,BL460,Reserved,0
5,BL460,Reserved,0
6,DL360,Available,1
7,DL360,Reserved,0
8,DL360,Reserved,0
Where Reserved is equal to 0, and Available is equal to 1. I only want the end-user to be able to checkout a server in Available status.
To the question: What I want to do in the page is present the list of servers on the page in this way, where Available is equal to the amount:
BL460 - Amount: 2
DL360 - Amount: 1
How can I achieve this format in PHP?
Another option is a crosstab query -
SELECT `Status`,
SUM(IF(`Server_Type` = 'BL460' AND `Status` = 'Available', `Amount`, 0)) AS `BL460`,
SUM(IF(`Server_Type` = 'DL360' AND `Status` = 'Available', `Amount`, 0)) AS `DL360`
FROM `products`
GROUP BY `Status`
Your table would look like this -
Status | BL460 | DL360 |
Available | 2 | 1 |
Reserved | 0 | 0 |
Here is an EXAMPLE
Even better would be to flip things around -
SELECT `server_type`,
SUM(IF(`status` = 'Available', 1, 0)) AS `Available`,
SUM(IF(`status` = 'Reserved', 1, 0)) AS `Reserved`
FROM `servers`
GROUP BY `server_type`;
Which would result in a table that looks like this (based on data in the fiddle) -
server_type | Available | Reserved
BL460 | 3 | 1
DL360 | 1 | 2
Here is that EXAMPLE
Here I could continue to add servers to the table without having to worry about adding them to the query as you would have to do in the first query. If you add an additional status you would have to change the query.
Note in both cases there is no need for an Amount column as the status is the item counted. By placing the load on the database server it makes it much easier to output the HTML as you are just going row bu row as you normally would.
Well, that would probably be easier if you do it directly in your SQL query:
SELECT Server_Type, COUNT(*) AS Count FROM products WHERE Status = 'Available' GROUP BY Server_Type
This should give you exactly the table you want.
If you want to do it in PHP, the easiest solution would probably be to loop through your SQL result and count the number of available servers per Server_Type in an associative array where the Server_Type is your array key:
$amounts = array();
foreach($sql_result as $entry) {
if($entry['Amount'] == 1) {
if(isset($amounts[$entry['Server_Type']])) {
$amounts[$entry['Server_Type']]++;
} else {
$amounts[$entry['Server_Type']] = 1;
}
}
}
echo $amounts;
Edit: in order to print the values as described in the question, you could use the following code snippet:
foreach($amounts as $name=>$amount) {
echo $name + " - Amount: " + $amount + "<br>";
}
This is what my customers_basket table looks like:
customers_id | products_id | basket_quantity
3 | 56:3121fefbe6043d6fc12e3b3de2c8fc38 | 3
3 | 56:fb4c9278fcfe6225b58c06711a7e62ef | 1
3 | 56:8e334fce09556108f5416e27154b6c27 | 1
3 | 52:f3b9f38e4ddd18035bc04cd264b0f052 | 1
This is the query I'm using:
$products_in_cart_query = "SELECT products_id FROM customers_basket WHERE customers_id = " . $_SESSION['customer_id'] ."";
$products_in_cart = $db->Execute($products_in_cart_query);
$products_in_cart_model = $products_in_cart->fields['products_id'];
$products_in_cart_model = substr($products_in_cart_model, 0, strpos($products_in_cart_model, ":"));
The end result I get is 56,56,56,52
First of all, how do I use the first line's quantity field? I'd need to list that products_id 3 times since quantity is 3. Therefore, the end result needs to be: 56,56,56,56,56,52
or, for easier understanding (56,56,56),56,56,52
And second, how do I count how many same values I have? In this case, I have 5x56 and 1x52. I need to use those counts in my further calculation.
EDIT: further calculations explained
I need to know how many of each product_id I have and then run something like this:
foreach(product_id) {
$shipping_cost += FIXED_VALUE * basket_qty;
}
To get the basket quantity, you have to select it. It would be best if the first portion of the product ID was stored in a separate column, rather than having to do messy operations like substringing.
Query 1: 2-character codes and corresponding quantities
SELECT SUBSTR(products_id, 1, 2) AS product_code, basket_quantity
FROM Customers_Basket
WHERE customers_id = 3;
Query 2: 2-character codes and summed quantities
SELECT product_code, SUM(basket_quantity) AS total_quantity
FROM (SELECT SUBSTR(products_id, 1, 2) AS product_code, basket_quantity
FROM Customers_Basket
WHERE customers_id = 3
)
GROUP BY product_code;
If you really, really, really desperately want 3 rows of data for the product ID 56:3121fefbe6043d6fc12e3b3de2c8fc38, then you have to know ways to generate rows. They're truly painful in the absence of convenient SQL support (so much so, that you'd do better to select a row in PHP with the quantity and then generate the appropriate number of rows in your array in the client-side (PHP) code). I'm going to assume that some variation on these queries will get you the information you want.
I have table of products, and there are 2 fields: price, currency. Possible values in currency fields are 1,2,3. 1 for MDL, 2 for USD, and 3 for EUR. I have to sort my products by price in mdl currency. So i have an array with rates:
$v = array(1,11.38,15.8);
Help my please with my query, I've tried something like this, but I've got errors:
$results = $this->Product
->query("SELECT `id`,`price`,`currency` FROM products
ORDER BY price*$v[currency] DESC");
Hmm... I`ll try to explain, through an example.
My table:
id|price|currency
_________________
1 | 500 | 2
2 | 300 | 3
It shows that first products price is saved in USD, and second products price is saved in EUR. But i have to sort them in MDL valute. So i get an array of rates for each value:
$rates = array([1] = > 1, [2] => 11.50, [3] => 15.50);
So i have to order my products by the result of formula: price*value rate
in first case: 500*$rates['currency value from db, in our case 2] = 500 * 11.50 etc.
Thanks in advance.
Because of the extended example on this problem I have edited this query.
Lets assume that the currencies are alse stored in some table, lets say currency (if not, it should be anyway).
Table currency should be as follows:
ID VALUE CODE
-----------------------------
1 1 USD
2 11.38 EUR
3 15.8 MDL
Then the query should be:
SELECT p.`id`, p.`price`, p.`price` * c.`value` AS 'ratio'
FROM products p
LEFT JOIN currency c ON c.`id` = p.`currency`
ORDER BY `ratio` DESC
By this query You select the currency value from the table currency depending on the currency ID from products table and finaly the results are ordered by the ration price * currency value.
I understand that maybe You have the currencies only hardcoded as array within some config, but it really would be better to put the currencies into the DB (if it is not).
You can`t use data base column name as array keys, because mysql is later instance than php. In php you simply generate query string that is passed to database managment system.
Your query should look like this:
$results = $this->Product->query
(
"SELECT `id`,`price`,
CASE `currency`
WHEN '1' THEN $v[0]
WHEN '2' THEN $v[1]
WHEN '3' THEN $v[2]
END AS 'ratio'
FROM products
ORDER BY price*ratio DESC
"
);