I have 3 tables:
PRICE
id price date
1 50 20130716
2 30 20130717
TVA
id val start end
1 7 20080101 20103112
2 8 20110101
MARGIN
id qty marg
1 500 25
2 600 20
3 800 15
4 1000 13
5 1250 11
...
Now I have this query which doesn't works:
$quantity = '557';
$link->query("
SELECT (
(price+marg)*((val+100)/100)
)
FROM PRICE
JOIN TVA
JOIN MARGIN
WHERE date = '20130717'
AND end = ''
AND qty = '$quantity'
");
The problem is that there isn't a qty = '557' on the table.
What I'd like to do is to select the most near quantity to (in this case) '557'.
So if:
$quantity = '557' the query should select 600
$quantity = '701' the query should select 800
$quantity = '1238' the query should select 1250
etc.
Is this possible?
If you put it into a procedure, you can use something like this (sort-of pseudocode):
CREATE PROCEDURE pDoStuff(#target INTEGER)
AS
DELCARE #qty INTEGER
-- Get closest qty
#qty = SELECT TOP 1 qty
FROM table
ORDER BY ABS(#target - qty) ASC
-- use that "actual" qty in your query
SELECT ((price+marg)*((val+100)/100)
FROM price
JOIN TVA
JOIN MARGIN
WHERE date = 'thedate'
AND end = ''
AND qty = #qty
GO
The syntax is incorrect, but it gives you an idea. This will allow you to select ALL rows from your original query with the closest quantity value. Most of the other answers here will limit your final results to one row (which may or may not be what you actually want).
...
AND `qty` <= $quantity
ORDER BY `qty` DESC
LIMIT 1
You can get value bigger than yours, ordered ascending and limit to 1 result. so you can firt value bigger or equal yours
SELECT (
(price+marg)*((val+100)/100)
)
FROM PRICE
JOIN TVA
JOIN MARGIN
WHERE date = '20130717'
AND end = ''
AND qty >= '$quantity'
ORDER BY qty ASC LIMIT 1
With same method you can get value lower than your number and see which one is closer to your qty
Related
I need a query that fetches data fron two tables and sort them by date.
Table 1: Invoice
<?php
$query = mysql_query("select * from invoice where customer = 95");
?>
ID Customer Amount Date
1 95 1500 01-Apr-2017
2 95 5500 09-Apr-2017
3 95 22000 10-Apr-2017
4 95 35000 11-Apr-2017
Table 2: Payments
<?php
$query = mysql_query("select * from Payments where customer = 95");
?>
ID Customer Amount Date
1 95 10000 02-Apr-2017
2 95 11000 09-Apr-2017
3 95 22000 11-Apr-2017
4 95 1200 15-Apr-2017
I need output as below:
ID Date InvoiceDR InvoiceCR
1 01-Apr-2017 1500 -
2 02-Apr-2017 - 10000
3 09-Apr-2017 5500 -
4 09-Apr-2017 - 11000
$query = mysql_query("SELECT * FROM (
(SELECT invoice.id, NULL AS invoiceDR, invoice.InvoiceCR, invoice.Date FROM invoice)
UNION ALL
(SELECT NULL AS id, paymentd.InvoiceCR, NULL AS InvoiceDR, payments.Date FROM Payments)
) results ORDER BY Date ASC");
put order by date in end of the query
and change order of date as per your need
You can use "order by" for this purpose. You can set order by ascending and descending (ASC or DESC). Use this query.
select * from Invoice,Payments where '{condition}' order by Invoice.Date ASC , Payemnts.Date ASC
This query will firstly sort the data according to first table(Invoice) and then sorted data will sorted with second table(Payemnts)
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
How can I select last (=max) value from column and count of all rows in single query?
ID ITEM_ID VALUE
1 1 100
2 1 101
3 2 201
4 3 333
5 2 222
6 1 111
I want to select last / max value for particular ITEM_ID and count of all rows with this ID.
For ITEM_ID = 1 thus:
VALUE COUNT
111 3
My query is like this:
SELECT (SELECT COUNT(*) FROM table) AS count, (SELECT value FROM table ORDER BY id DESC LIMIT 1) AS value FROM table WHERE item_id = 1 LIMIT 1
It works but looks ... weird. Is there any better (simpler / faster) solution? Thanks
You need to do a GROUP BY on column ITEM_ID while getting the MAX() and COUNT() like
select max(value) as `VALUE`,
count(*) as `COUNT`
from your_table
group by ITEM_ID;
I have following records in my table:
Name Status Price
Product 1 Active 110
Product 2 Active 165
Product 3 Expire 256
Product 4 Pending 154
Product 5 Active 856
Product 6 Expire 523
Product 7 Pending 220
Product 8 Active 321
Product 9 Pending 478
Product 10 Expire 210
and I need output by mysql query as follow:
Status Low Median Average High
Active ? ? ? ?
Expire ? ? ? ?
Pending ? ? ? ?
I don't know how to do this by mysql query.
Thanks in advance.
SELECT status, MIN(price) as Low, MAX(price) as High, AVG(price) as Average
FROM your_table
GROUP BY status
try following code:
<?php
$arr = array( 'Active', 'Expire', 'Pending');
foreach($arr as $status) {
$stmt = "SELECT a.max, a.min, a.avg, price AS med, IF(price > a.avg, price - a.avg, a.avg-price ) AS diff FROM tbl_report_address_lists, ( SELECT ROUND(AVG(price),2) as avg, MAX(price) AS max, MIN(price) AS min FROM tbl_report_address_lists WHERE `report_id` = 13 AND `status` = '$status') AS a WHERE `report_id` = 13 AND `sales_code` = '$status' ORDER BY diff ASC LIMIT 1";
// execute query, get result data and use it
}
?>
I have prepared following query to calculate High, Low, Med and Avg, but this query calculate prices only for single status at a time:
SELECT STATUS , a.max AS High, a.min AS Low, a.avg AS Avg, Price AS Med, IF( Price > a.avg, Price - a.avg, a.avg - Price ) AS diff
FROM Table, (
SELECT ROUND( AVG( Price ) , 2 ) AS avg, MAX( Price ) AS max, MIN( Price ) AS min
FROM Table
WHERE STATUS = 'Pending'
) AS a
WHERE STATUS = 'Pending'
ORDER BY diff ASC
LIMIT 1
If I removed WHERE STATUS = 'Pending' condition, return inaccurate result.
I have this table
UMS
id_attribute value order
1 MB 1
1 Gb 2
1 TB 3
...
and this table
ATTRIBUTE_VALUE
id id_attribute value name ums
1 1 50 hdd GB
2 1 100 hdd TB
3 2 15.00 price NULL
and i want to select from ATTRIBUTE_VALUE where id_attribute=1 and if exist (UMS.value=ATTRIBUTE_VALUE.ums) then order by UMS.order end if group by ATTRIBUTE_VALUE.value
example for output :
50 GB
100 Tb
and must to appear
15.00 !!! here is the problem because in my UMS table i don't have UMS for price
but it doesn't appear
Update after you clarified your question - Try something like this:
SELECT T1.*
FROM ATTRIBUTE_VALUE T1
LEFT JOIN UMS T2
ON T1.id_attribute = T2.id_attribute AND T1.ums = T2.value
ORDER BY T2.order, T1.value
But note that this will fail if T1.value is greater than 1000. It might be better to convert all units to the same type before ordering them.
Result of query:
id id_attribute value name ums
3 2 15.00 price
1 1 50 hdd GB
2 1 100 hdd TB
You can make a conditional order by in mysql, like this, for example:
user
id name
select *
from user
order by (case when id <5 then id else name end)
However, you've got two tables, you need yo join them, I'm still not sure if you can get what you need this way.
Also, you can't order with DESC on one branch and ASC on another.
Finlay I have get my own answer:
this is the code:
$nr_ordine=0;
$virgula="";
$ordine="valoare";
$ordine2="FIELD(unitate_masura,";
$sql_ums=mysql_query("select * from atribute_masura where id_atribut='".$exe_atribut['id']."' order by ordine asc");
while($exe_ums=mysql_fetch_array($sql_ums))
{
$nr_ordine++;
if($nr_ordine>1)
{
$virgula=",";
};
$ordine2.=$virgula."'".$exe_ums['valoare']."'";
};
$ordine2.=")";
if($ordine2!="FIELD(unitate_masura,)")
{
$ordine=$ordine2;
};
$s_q0=mysql_query("select * from atribute_cautare where id_atribut='".$exe_atribut['id']."' group by valoare order by $ordine asc") or die (mysql_error());
while($s_q=mysql_fetch_array($s_q0))
{
...
};
The names not correspond with my question but this is the idea order by FIELD (ums,'kb','mb','gb','tb')