MySQL join next lower value from other table - mysql

I've the two tables orders
id article amount
1 1 1
2 2 50
and prices
id article min_amount price
1 1 1 42.99
2 2 1 5.06
3 2 5 4.55
4 2 10 4.3
5 2 25 4.05
6 2 100 2.66
The prices tables contains IDs of articles and a minimum amount you would have to buy to get a bulk discount (which would change the price for the order). I would like to join prices into orders, so that the result looks like:
id article amount price
1 1 1 42.99
2 2 50 4.05
The order id 2 is above the minimum (25) to get the article for 4.05€, but still below 100 at which you would get a bigger discount, so the query would to have pick the next-lower value.
I've tried this query so far
SELECT
orders.id AS id,
orders.article,
orders.amount,
prices.price,
(orders.amount - prices.min_amount) AS discount_diff
FROM orders
LEFT JOIN prices ON (prices.article = orders.article) AND (prices.min_amount <= orders.amount)
which gives this result
id article amount price discount_diff
1 1 1 42.99 0
2 2 50 5.06 49
2 2 50 4.55 45
2 2 50 4.3 40
2 2 50 4.05 25
You can find this example on "js"fiddle: http://sqlfiddle.com/#!9/1b2bf/8

The query you need is this:
SELECT orders.id AS id,
orders.article,
orders.amount,
prices.price
FROM orders
INNER JOIN prices ON ( prices.article = orders.article
and prices.min_amount <= orders.amount)
INNER JOIN ( SELECT orders.article,
orders.amount,
min(prices.price) minprince
FROM orders
INNER JOIN prices ON (prices.article = orders.article
AND prices.min_amount <= orders.amount)
GROUP BY orders.article,
orders.amount) b
ON ( prices.article = b.article
AND orders.amount = b.amount
AND prices.price = b.minprince)
See it here: http://sqlfiddle.com/#!9/1b2bf/27

Related

Use aggregate functions with group by from several tables

I have the following tables to allow the subscriber to sell products through the application
Order Table
OrderId
Date
1
2021-07-10
2
2021-08-24
Approval table
ApprovalId
OrderId
Status
SellerId
1
1
Accepted
10
2
1
Rejected
20
3
2
Accepted
30
Item table
ItemId
OrderId
Price
Qty
SellerId
1
1
620$
1
10
2
1
150$
2
10
3
1
410$
1
20
4
2
220$
1
30
what i want is to display the income revenue for > only who accept the order
Date
Sales
Seller_Part 90%
Net_Sales 10%
2021-07-10
770$
693$
77$
2021-08-24
220$
198%
22$
I tried using aggregate functions with group by but the result include rejected order also
select o.date
,sum(i.price * i.qty) sales
,sum(i.price * i.qty) * 0.90 Seller_Part90%
,sum(i.price * i.qty) * 0.10 Net_Sales10%
from Order o
join Approval a
on o.orderId = a.OrderId
and a.status= 'Accepted'
join Items i
on a.sellerid = i.sellerid
and a.orderid = i.orderid
group by o.date

MySQL find MIN() from duplicate rows

I have 3 tables like below:
Product Table
PID CODE
1 a
2 b
Price Table
PrID PID(ID from Product) UMID(ID from UOM) Price
1 1 1 10
2 1 2 5
3 2 1 10
UOM Table
UMID UM_NAME UM_RATE
1 BOX 5
2 PC 10
I want to get product with price and that uom which has min UM_RATE. For example, product CODE a has two prices but the prices are different for different uom. What I want to achieve is,
PID CODE PrID Price UM_NAME UM_RATE
1 a 1 10 BOX 5
2 b 3 10 BOX 5
Because box has min UM_RATE. I have tried the following query,
SELECT product.*, price.*, uom.um_name, MIN(uom.um_rate)
FROM product
LEFT JOIN price ON price.pid = product.pid
LEFT JOIN uom ON price.umid = uom.umid
GROUP BY product.pid
This query gives me the following result,
PID CODE PrID Price UM_NAME UM_RATE
1 a 1 10 PC 5
2 b 3 10 BOX 5
which is wrong. because UM_RATE 5 is belong to UM_NAME box.
How can I get the expected result?
use join and corelated subquery
select * from (select distinct p.*,u.UMID as uid,
u.UM_NAME,u.UM_RATE,pr.code from
price p join uom u on p.UMID=u.UMID
join product pr on pr.PID=p.PID
) a
where a.UM_RATE =(select min(UM_RATE) from
(select p.*,u.UMID as uid,
u.UM_NAME,u.UM_RATE,pr.code from
price p join uom u on p.UMID=u.UMID
join product pr on pr.PID=p.PID) t where t.code=a.code
)
prid PID UMID price uid UM_NAME UM_RATE code
1 1 1 10 1 Box 5 a
3 2 1 10 1 Box 5 b

How to use multiple aggregate function with group by

I have three tables in advertiser,advertiser_clicks and advertiser_cost in which i have used join with multiple aggregate function.But i was unable to get the actual record from the tables.Please find below my table structure.
Table1:advertiser
................
id name
................
1 Your Survey
2 Vindale
Table2:advertiser_clicks
In this table adv_id is foreign key of advertiser table id
.............................................................
id adv_id survey_id survey_name clicks dt_datetime
.............................................................
1 1 101 survey1 1 2017-11-30
2 2 102 survey2 1 2017-11-29
3 1 103 survey3 1 2017-11-28
Table3:advertiser_cost
In this table a_click_id is the foreign key of advertiser_clicks table adv_id
.......................................................
ac_id a_click_id cpi conversion cost profit
......................................................
1 1 10 1 8 2
2 2 10 1 5 5
3 3 5 1 5 5
I want below output:-when i select start date:2017-11-29 and enddate :2017-11-30 in where condition then i want below output.Here total click,cpi,cost & profit is the sum of all the data which comes in between that daterange.
.............................................................
adv_id advertiser totalclick cpi cost profit
.............................................................
1 Your survey 2 20 13 8
2 vindale 0 0 0 0
I have write the below query which returns the exact data which comes
in between that date range but i it will not return the record of vindale
advertiser as a zero value.Please find my below query.
SELECT sum(advertiser_clicks.`clicks`) as totalclick,sum(advertiser_cost.cpi) as revenue,sum(advertiser_cost.`conversion`) as conversion,sum(advertiser_cost.`cost`) as cost,SUM(advertiser_cost.profit) as profit,advertiser.name as advertiser,advertiser.id as adv_id FROM `advertiser_clicks` LEFT JOIN advertiser_cost on advertiser_cost.a_click_id=advertiser_clicks.`id` inner join advertiser on advertiser.id=advertiser_clicks.`adv_id` where advertiser_clicks.`dt_datetime`>='2017-11-29' and advertiser_clicks.`dt_datetime`<='2017-11-30' group by advertiser.name,advertiser.id
My query return this output:-
.............................................................
adv_id advertiser totalclick cpi cost profit
.............................................................
1 Your survey 2 20 13 8
Hi i have resolved my issue:-
SELECT sum(advertiser_clicks.`clicks`) as totalclick,sum(advertiser_cost.cpi) as revenue,sum(advertiser_cost.`conversion`) as conversion,sum(advertiser_cost.`cost`) as cost,SUM(advertiser_cost.profit) as profit,advertiser.name as advertiser,advertiser.id as adv_id FROM `advertiser` left join advertiser_clicks on advertiser.id=advertiser_clicks.`adv_id` and (advertiser_clicks.`dt_datetime` between '$startdate' and '$enddate' ) LEFT JOIN advertiser_cost on advertiser_cost.a_click_id=advertiser_clicks.`id` group by advertiser.name,advertiser.id

MYSQL: View statement produces incorrect SUM totals

I have 3 tables. A table for product prices, invoiced products, and ordered products. I am trying to create a view that joins these. I want to output the product prices with a total of invoiced products and a total of ordered products.
products_price
id season_id product_id product_price
1 1 1 3.99
2 1 2 6.99
3 1 3 5.99
4 1 4 5.99
....
invoices_products
id season_id invoice_id product_id piece_qty
1 1 1 1 1600
2 1 2 2 3200
3 1 3 2 200
4 1 4 1 120
....
orders_products
id season_id order_id product_id piece_qty
1 1 1 1 160
2 1 2 1 40
3 1 2 2 20
4 1 3 2 10
....
Here are a few queries from the View statements I've tried so far.
This query gives me everything I want. The View's output is perfect but the SUM() for the first 2 rows is off. total_invoice_product is double for row 1 and 2. total_order_productis 4x for row 1 and 3x for row 2.
Statement 1:
SELECT
`t1`.`id` AS `id`,
`t1`.`season_id` AS `season_id`,
`t1`.`product_id` AS `product_id`,
`t1`.`product_piece_price` AS `product_piece_price`,
SUM(`t2`.`piece_qty`) AS `total_invoice_product`,
SUM(`t3`.`piece_qty`) AS `total_order_product`
FROM
((`products_price` `t1`
LEFT JOIN `invoices_products` `t2` ON (((`t2`.`product_id` = `t1`.`product_id`)
AND (`t2`.`season_id` = `t1`.`season_id`))))
LEFT JOIN `orders_products` `t3` ON (((`t3`.`product_id` = `t1`.`product_id`)
AND (`t3`.`season_id` = `t1`.`season_id`))))
GROUP BY `t1`.`season_id` , `t1`.`product_id`
This query gives me the output that I expect. Its not the full output I want but its correct for the statement. The SUM() totals are off on this one as well.
Statement 2:
SELECT
`t1`.`id` AS `id`,
`t1`.`season_id` AS `season_id`,
`t1`.`product_id` AS `product_id`,
`t1`.`product_price` AS `product_price`,
SUM(`t2`.`piece_qty`) AS `total_invoice_product`,
SUM(`t3`.`piece_qty`) AS `total_order_product`
FROM
((`products_price` `t1`
LEFT JOIN `invoices_products` `t2` ON ((`t2`.`product_id` = `t1`.`product_id`)))
LEFT JOIN `orders_products` `t3` ON ((`t3`.`product_id` = `t1`.`product_id`)))
WHERE
((`t2`.`season_id` = `t1`.`season_id`)
AND (`t2`.`product_id` = `t1`.`product_id`))
GROUP BY `t1`.`season_id` , `t1`.`product_id`
the output I want
id season_id product_id product_price total_invoice total_order
1 1 1 3.99 1720 200
2 1 2 6.99 3400 30
3 1 3 5.99 576
4 1 4 5.99 800
output received for statement 1
id season_id product_id product_price total_invoice total_order
1 1 1 3.99 3440 800
2 1 2 6.99 6800 90
3 1 3 5.99 576
4 1 4 5.99 800
output received for statement 2
id season_id product_id product_price total_invoice total_order
1 1 1 3.99 3440 800
2 1 2 6.99 6800 90
I can build a query like below and it works perfect. I get the exact output I need but this code does not work as a view. I get this error: ERROR 1349: View's SELECT contains a subquery in the FROM clause SQL Statement
Perfect Query but will not work as a view
SELECT
products_price.id,
products_price.season_id,
products_price.product_id,
products_price.product_price,
invoices_grouped.total_invoice_product,
orders_grouped.total_order_product
FROM
products_price
LEFT JOIN
(SELECT
invoices_products.product_id,
invoices_products.season_id,
SUM(invoices_products.piece_qty) AS total_invoice_product
FROM
invoices_products
GROUP BY
invoices_products.product_id) AS invoices_grouped
ON
invoices_grouped.product_id = products_price.product_id
AND
invoices_grouped.season_id = products_price.season_id
LEFT JOIN
(SELECT
orders_products.product_id,
orders_products.season_id,
SUM(orders_products.piece_qty) AS total_order_product
FROM
orders_products
GROUP BY
orders_products.product_id) AS orders_grouped
ON
orders_grouped.product_id = products_price.product_id
AND
orders_grouped.season_id = products_price.season_id
What I need
I've tried several other statements. They either got worse results or the same. Can someone help me get Statement 1 working with a proper SUM?
Edit 1 for a question
The information that this view provides will be called upon a lot. The products_price and invcoices_products tables will not be changed that often. orders_products will be changed a lot. If 2 views are required, would it be more efficient to use the "Perfect" query above or use 2 views?
Edit 2 for another query
Here is another query from my view statement. This query is part of Statement 1 shown above. This query works perfect but it is not complete. I need the second SUM column. When you add the second LEFT JOIN it breaks the SUM totals.
SELECT
`t1`.`id` AS `id`,
`t1`.`season_id` AS `season_id`,
`t1`.`product_id` AS `product_id`,
`t1`.`product_piece_price` AS `product_piece_price`,
SUM(`t2`.`piece_qty`) AS `total_invoice_product`
FROM
(`products_price` `t1`
LEFT JOIN `invoices_products` `t2` ON (((`t2`.`product_id` = `t1`.`product_id`)
AND (`t2`.`season_id` = `t1`.`season_id`))))
GROUP BY `t1`.`season_id` , `t1`.`product_id`
output
id season_id product_id product_price total_invoice
1 1 1 3.99 1720
2 1 2 6.99 3400
3 1 3 5.99 576
4 1 4 5.99 800
Well, MySql has some limitations, so you will need to create 2 views for subqueries and use them:
create view viewInvoices
as
select season_id, product_id, sum(piece_qty) pq
from invoices_products group by season_id, product_id
create view viewOrders
as
select season_id, product_id, sum(piece_qty) pq
from orders_products group by season_id, product_id
select pp.id,
pp.season_id,
pp.product_id,
pp.product_price,
i.pq as total_invoice,
o.pq as total_order
from products_price pp
left join viewInvoices as i
on pp.season_id = i.season_id and pp.product_id = i.product_id
left join viewOrders as o
on pp.season_id = o.season_id and pp.product_id = o.product_id
Try this query
SELECT * from products_price as a left join (select product_id, sum(piece_qty)total_invoices from invoices_products group by product_id) as b on a.product_id=b.product_id left join (select product_id, sum(piece_qty) as total_order from orders_products group by product_id) as c on a.product_id=c.product_id

SQL select from tables

I've got tables:
Table1= USER_ID ITEM_ID
1 12
1 13
2 12
3 12
3 1
3 2
etc..
And second table:
Products = ITEM_ID PRICE
1 1.3
2 0.1
4 22
12 33
13 45
It is just example. How can I get ID's of clients who paid more than average order value?
I tried many times, but I always get errors.
You can do a JOIN between the tables and comparing the average price with specific user price paid like
select t1.user_id
from table1 t1
join products p on t1.item_id = p.item_id
group by t1.user_id
having p.price > avg(p.price);