Query to get data from four tables - mysql

i have following scheme,
purchase_order
+-------------------+----------------------+
| purchase_order_id | purchase_order |
+-------------------+----------------------+
| 54 | Purchase Order 12345 |
| 56 | po-laptop-hp-3 |
| 57 | po-laptop-hp-1 |
+-------------------+----------------------+
purchase_order_detail
+--------------------------+-------------------+---------+------------------+
| purchase_order_detail_id | purchase_order_id | item_id | ordered_quantity |
+--------------------------+-------------------+---------+------------------+
| 61 | 54 | 279 | 500 |
| 62 | 54 | 286 | 700 |
| 63 | 56 | 279 | 43 |
| 64 | 57 | 279 | 43 |
| 65 | 57 | 286 | 43 |
| 66 | 57 | 287 | 43 |
+--------------------------+-------------------+---------+------------------+
delivery_order
+-------------------+--------------------------+-------------------+
| delivery_order_id | purchase_order_detail_id | recieved_quantity |
+-------------------+--------------------------+-------------------+
| 62 | 61 | 250 |
| 63 | 62 | 300 |
| 64 | 63 | 34 |
| 65 | 64 | 34 |
| 66 | 65 | 34 |
| 67 | 66 | 34 |
| 68 | 61 | 34 |
| 69 | 61 | 34 |
+-------------------+--------------------------+-------------------+
stock
+----------+-------------------+------------+----------+------------------+---------------+
| stock_id | delivery_order_id | project_id | quantity | initial_quantity | stock_type_id |
+----------+-------------------+------------+----------+------------------+---------------+
| 12 | 62 | 1 | 60 | 60 | 1 |
| 13 | 63 | 1 | 120 | 120 | 1 |
| 14 | 63 | 1 | 50 | 50 | 1 |
| 15 | 64 | 1 | 12 | 12 | 1 |
| 16 | 62 | 1 | 120 | 120 | 1 |
| 17 | 62 | 1 | 12 | 12 | 1 |
+----------+-------------------+------------+----------+------------------+---------------+
i have write this query but it returns duplicate results
SELECT po.created_on
, po.purchase_order
, i.item_name
, u.unit_name
, pod.ordered_quantity
, do.recieved_quantity
, do.recieved_on
, po.remarks
FROM purchase_order po
, purchase_order_detail pod
, delivery_order do
, stock s
, item i
, unit u
WHERE u.unit_id = i.unit_id
AND i.item_id = pod.item_id
AND po.purchase_order_id = pod.purchase_order_id
AND pod.purchase_order_detail_id = do.purchase_order_detail_id
AND do.delivery_order_id = s.delivery_order_id
AND s.project_id = 1
ORDER BY po.purchase_order_id
, pod.item_id
;
The results
+---------------------+----------------------+------------+-----------+------------------+-------------------+---------------------+---------------------------------------+
| created_on | purchase_order | item_name | unit_name | ordered_quantity | recieved_quantity | recieved_on | remarks |
+---------------------+----------------------+------------+-----------+------------------+-------------------+---------------------+---------------------------------------+
| 2015-02-24 22:48:15 | Purchase Order 12345 | HP Laptops | Unit | 500 | 250 | 2015-02-21 00:00:00 | Adding first Purchase Order as a Test |
| 2015-02-24 22:48:15 | Purchase Order 12345 | HP Laptops | Unit | 500 | 250 | 2015-02-21 00:00:00 | Adding first Purchase Order as a Test |
| 2015-02-24 22:48:15 | Purchase Order 12345 | Lenovo | Unit | 700 | 300 | 2015-02-21 00:00:00 | Adding first Purchase Order as a Test |
| 2015-02-24 22:48:15 | Purchase Order 12345 | Lenovo | Unit | 700 | 300 | 2015-02-21 00:00:00 | Adding first Purchase Order as a Test |
| 2015-02-24 22:55:40 | po-laptop-hp-3 | HP Laptops | Unit | 43 | 34 | 2015-02-21 00:00:00 | dfgsdfgsd |
+---------------------+----------------------+------------+-----------+------------------+-------------------+---------------------+---------------------------------------+
relationship is one to many from top to bottom.
What I wanted to get is the each purchase_order , his ordered quantity of each item, and total recieved quantity, and quantity in stock where project_id = 1 from stock.
i am expecting something like this,
+-------------------+---------+------------------+---------------+----------+
| purchase_order_id | item_id | ordered_quantity | totalReceived | quantity |
+-------------------+---------+------------------+---------------+----------+
| 54 | 279 | 500 | 314 | 192 |
| 54 | 286 | 700 | 300 | 170 |
| 56 | 279 | 43 | 34 | 12 |
+-------------------+---------+------------------+---------------+----------+

EDIT
Thank you for clearing up the mistake in my first part. I realize now that we cannot do all calculations in a single query (because we group on different columns in various parts) so I started by writing individual subqueries and joining them together. The steps went something like this:
Get the sum of received total received quantity for each
purchase_order_detail_id from the delivery_order table.
Join that subquery with the delivery_order table itself to get the totalReceived for the various delivery_order_id values.
Join that result set with the purchase_order_detail table to get the purchase_order_id, item_id, and ordered_quantity for each delivery_order_id.
We now have a result set including the delivery_order_id, purchase_order_id, item_id, ordered_quantity, and total received. The last two things are:
Get the SUM() of quantity for each delivery_order_id from the stock table.
Join that with our above result set on the condition that order_id matches (so we will only get one row) and that project_id is 1 (so we only get the necessary delivery_order_id values). I put that condition in the WHERE clause of the sum subquery.
Here is your final query:
SELECT tmp1.purchase_order_id, tmp1.item_id, tmp1.ordered_quantity, tmp1.totalReceived, tmp2.quantity
FROM(
SELECT tmp.delivery_order_id, pod.purchase_order_id, pod.item_id, pod.ordered_quantity, tmp.totalReceived
FROM purchase_order_detail pod
JOIN(
SELECT do.delivery_order_id, tmp.purchase_order_detail_id, tmp.totalReceived
FROM delivery_order do
JOIN(
SELECT do.purchase_order_detail_id, SUM(do.received_quantity) AS totalReceived
FROM delivery_order do
GROUP BY do.purchase_order_detail_id) tmp ON tmp.purchase_order_detail_id = do.purchase_order_detail_id)
tmp ON tmp.purchase_order_detail_id = pod.purchase_order_detail_id) tmp1
JOIN(
SELECT s.delivery_order_id, SUM(quantity) AS quantity
FROM stock s
WHERE s.project_id = 1
GROUP BY s.delivery_order_id) tmp2 ON tmp2.delivery_order_id = tmp1.delivery_order_id;
Here is the SQL Fiddle. It shows all of the intermediate steps too, if you'd like to see how the results came together individually.

Try modifying your query to use DISTINCT and OUTER JOINs instead of cartesian ("comma") joins.
SELECT DISTINCT po.created_on
, po.purchase_order
, i.item_name
, u.unit_name
, pod.ordered_quantity
, do.recieved_quantity
, do.recieved_on
, po.remarks
FROM purchase_order po
LEFT JOIN purchase_order_detail pod USING (purchase_order_id)
LEFT JOIN delivery_order do USING (purchase_order_detail_id)
LEFT JOIN stock s USING (delivery_order_id)
LEFT JOIN item i USING (item_id)
LEFT JOIN unit u USING (unit_id)
ORDER BY po.purchase_order_id
, pod.item_id
;

Related

GROUP sum BY two tables by joining

I'm trying to write a SQL query that will correctly group sales items sold_qyt and sub-total-price together as per product's category so I can show this on the printable invoice that product from Jelly Sheet = 4 at a rate of 62 subtotal for this category product is 248(4 * 62 = 248). but when I try to run the below-mentioned query it shows out-put as 12 but I want subtotal and sold_qyt segregated base on category.
I have tried to run different queries just one query gives the output which is mentioned below and this is for just the sum of all sold_qyt. DB example is also shown below
DB Example: (For better understanding)
Table # 1:
Category
ID | code | name
1 | 1 | jelly sheet
2 | 2 | 9D Glass
3 | 3 | Polished Glass
Table # 2:
Product:
ID | code | name | cost | category_id | price
1 | 1 | IP11JS | 50 | 1 | 62
2 | 2 | IP12JS | 50 | 1 | 62
3 | 3 | IP119D | 40 | 2 | 55
4 | 4 | IP129D | 40 | 2 | 55
5 | 5 | IP11PG | 18 | 3 | 25
6 | 6 | IP12PG | 18 | 3 | 25
Table # 3:
sale_items:
ID | sale_id | product_id | product_code | product_name | unit_price | sold_qyt | subtotal |
1 | 1 | 1 | 1 | IP11JS | 62 | 2 | 124 |
2 | 1 | 2 | 2 | IP12JS | 62 | 2 | 124 |
3 | 1 | 3 | 3 | IP119D | 55 | 2 | 110 |
4 | 1 | 4 | 4 | IP129D | 55 | 2 | 110 |
5 | 1 | 5 | 5 | IP11PG | 25 | 2 | 50 |
6 | 1 | 6 | 6 | IP12PG | 25 | 2 | 50 |
7 | 2 | 7 | 1 | IP11JS | 62 | 2 | 124 |
8 | 2 | 8 | 2 | IP12JS | 62 | 2 | 124 |
9 | 2 | 9 | 3 | IP119D | 55 | 2 | 110 |
10 | 2 | 10 | 4 | IP129D | 55 | 2 | 110 |
11 | 2 | 11 | 5 | IP11PG | 25 | 2 | 50 |
12 | 2 | 12 | 6 | IP12PG | 25 | 2 | 50 |
SQL Query which is run by me:
SELECT sale_id,
SUM(sold_qyt) AS sold_qyt
FROM sale_items
GROUP BY sale_id
kindly help me with this difficulty thanks in advance
Update: 1-21-2021
i execute new query
SELECT (sma_sale_items.sale_id, sma_categories.code AS sma_products.category_id, sma_products.code AS sma_sale_items.product_code,)
SUM(sold_qyt) AS sold_qyt
SUM(subtotal) AS subtotal
FROM sma_sale_items
LEFT JOIN sma_products ON sma_products.id=sma_sale_items.product_id
LEFT JOIN sma_categories ON sma_categories.code=sma_products.category_id
GROUP BY sma_sale_items.sale_id
ORDER BY sma_categories
but no luck :(
I want the output like this:
Expected OUT PUT:
ID | sale_id | category_name | sold_qyt | subtotal |
1 | 1 | Jelly Sheet | 4 | 248 |
2 | 1 | 9D Glass | 4 | 220 |
3 | 1 | Polished Glass | 4 | 100 |
4 | 2 | Jelly Sheet | 4 | 248 |
5 | 2 | 9D Glass | 4 | 220 |
6 | 2 | Polished Glass | 4 | 100 |
The ID column in your expected result set is very misleading - it appears to be just new ID value for the output result set rather than any of the ID values from the source tables.
If it is important for you then you can use this query:
SELECT ROW_NUMBER() OVER (ORDER BY sale_id, category_id),
sale_id,
category_name,
sold_qty,
subtotal
FROM (
SELECT c.ID as category_id,
si.sale_id,
c.[name] as category_name,
SUM(si.sold_qty) as sold_qty,
SUM(si.subtotal) as subtotal
FROM sale_items si
JOIN product p ON p.ID = si.product_code
JOIN category c ON c.ID = p.category_id
GROUP BY c.ID,
si.sale_id,
c.[name]
) r
If it is not relevant and you only want the sale_id, category_name and the totals then simplify it to:
SELECT si.sale_id,
c.[name] as category_name,
SUM(si.sold_qty) as sold_qty,
SUM(si.subtotal) as subtotal
FROM sale_items si
JOIN product p ON p.ID = si.product_code
JOIN category c ON c.ID = p.category_id
GROUP BY si.sale_id,
c.[name]
ORDER BY sale_id, category_name

MySQL: I have two tables, 1 production and 1 archive. I need to select distinct records from both as some records are identical

I have a MySQL database containing 2 tables. prod is an in-production and archive has archived records. The columns are exactly the same. prod does not have all records in archive.
I need to access distinct records in 1 join of the two tables so I'm not duplicating records and throwing calculations off in excel.
SELECT
a.order_no,
a.date_of_sale,
a.cost,
b.order_no,
b.date_of_sale,
b.cost
FROM
`prod` AS a
LEFT JOIN `archive` AS b ON a.order_no = b.order_no
Results:
+----------+--------------+------+-------------+-----------------+---------+
| order_no | date_of_sale | cost | order_no(1) | date_of_sale(2) | cost(2) |
+----------+--------------+------+-------------+-----------------+---------+
| 333 | 11-28-2017 | 10 | 333 | 11-28-2017 | 10 |
| 334 | 11-28-2017 | 12 | 334 | 11-28-2017 | 12 |
| 336 | 11-29-2017 | 30 | 335 | 11-28-2017 | 25 |
| 337 | 11-30-2017 | 15 | | | |
| 338 | 11-30-2017 | 17 | 338 | 11-28-2017 | 17 |
+----------+--------------+------+-------------+-----------------+---------+
How can I structure my query to filter records that are the same in both tables?
The result I'd like:
+----------+--------------+------+
| order_no | date_of_sale | cost |
+----------+--------------+------+
| 333 | 11-28-2017 | 10 |
| 334 | 11-28-2017 | 12 |
| 335 | 11-28-2017 | 25 |
| 336 | 11-29-2017 | 30 |
| 337 | 11-30-2017 | 15 |
| 338 | 11-30-2017 | 17 |
+----------+--------------+------+```
I suspect that you want union rather than a join:
select order_no, date_of_sale, cost from prod
union
select order_no, date_of_sale, cost from archive
union removes duplicates between the resultsets (and within the resultsets as well).

Subtract two columns of different tables with different number of rows

How can I write a single query that will give me SUM(Entrance.quantity) - SUM(Buying.quantity) group by product_id.
The problem is in rows that not exist in the first or second table. Is possible to do this?
Entrance:
+---+--------------+---------+
| id | product_id | quantity|
+---+--------------+---------+
| 1 | 234 | 15 |
| 2 | 234 | 35 |
| 3 | 237 | 12 |
| 4 | 237 | 18 |
| 5 | 101 | 10 |
| 6 | 150 | 12 |
+---+--------------+---------+
Buying:
+---+------------+-------------+
| id | product_id | quantity|
+---+------------+-------------+
| 1 | 234 | 10 |
| 2 | 234 | 20 |
| 3 | 237 | 10 |
| 4 | 237 | 10 |
| 5 | 120 | 15 |
+---+------------+------------+
Desired result:
+--------------+-----------------------+
| product_id | quantity_balance |
+--------------+-----------------------+
| 234 | 20 |
| 237 | 10 |
| 101 | 10 |
| 150 | 12 |
| 120 | -15 |
+--------------+-----------------------+
This is tricky, because products could be in one table but not the other. One method uses union all and group by:
select product_id, sum(quantity)
from ((select e.product_id, quantity
from entrance e
) union all
(select b.product_id, - b.quantity
from buying b
)
) eb
group by product_id;
SELECT product_id ,
( Tmp1.enterquantity - Tmp2.buyquantity ) AS Quantity_balance
FROM entrance e1
CROSS APPLY ( SELECT SUM(quantity) AS enterquantity
FROM Entrance e2
WHERE e1.product_id = e2.product_id
) Tmp1
CROSS APPLY ( SELECT SUM(quantity) AS buyquantity
FROM Buying b2
WHERE e1.product_id = b2.product_id
) Tmp2
GROUP BY Product_id,( Tmp1.enterquantity - Tmp2.buyquantity )

Select the entire row of the lowest price for distinct product

I have the below table about products:
| id | name | product_id | price | seller_id | discount_id |
--------------------------------------------------------------
| 1 | phone | 11 | 400 | 7 | 19 |
| 2 | cpu | 78 | 120 | 33 | 4 |
| 3 | phone | 11 | 380 | 8 | 22 |
| 4 | phone | 11 | 460 | 5 | 19 |
| 5 | memory | 80 | 45 | 12 | 16 |
| 6 | router | 98 | 115 | 7 | 16 |
| 7 | cpu | 78 | 115 | 33 | 66 |
I need to select all the columns of distinct product_id with the lowest price. Also to ORDER the result by price ASC. For this example:
| id | name | product_id | price | seller_id | discount_id |
--------------------------------------------------------------
| 5 | memory | 80 | 45 | 12 | 16 |
| 6 | router | 98 | 115 | 7 | 16 |
| 7 | cpu | 78 | 115 | 33 | 66 |
| 3 | phone | 11 | 380 | 8 | 22 |
I have no problems doing this using GROUP BY product_id and min(price) but I also need other columns (seller_id & discount_id)
MySQL version: 5.7.17
sql_mode=only_full_group_by
Table is temporary (ENGINE=MEMORY) and can't JOIN multiple times
How can I produce the result above from MySQL?
Add a subquery with the min price and join on min price and product.
SELECT id, name,product_id,price,seller_id,discount_id FROM t
JOIN
(SELECT tt.product_id,MIN(tt.price) minp FROM t as tt
GROUP BY tt.product_id)x
ON x.product_id=t.product_id AND x.price = t.price
Another option with LIMIT
SELECT * FROM T WHERE EXISTS
(SELECT 1 FROM T as TT ORDER BY TT.price ASC LIMIT 1
WHERE t.id= TT.id)
Given that the MEMORY engine is so restricting go the caveman way
SELECT SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY price),',',1),
SUBSTRING_INDEX(GROUP_CONCAT(name ORDER BY price),',',1),
product_id,MIN(price),
SUBSTRING_INDEX(GROUP_CONCAT(seller_id ORDER BY price),',',1),
SUBSTRING_INDEX(GROUP_CONCAT(discount_id ORDER BY price),',',1) FROM t
GROUP BY product_id
You can join the table with itself (on product_id). As a join-condition add left.price > right.price - and then choose the rows, where right.price is null, because for that join, there is no lower right price, meaning the one you have left is the lowest:
SELECT l.id, l.name, l.product_id, l.price, l.seller_id, l.discount_id
FROM
products l
LEFT JOIN
products r
on
l.product_id = r.product_id AND l.price > r.price
WHERE
isnull (r.price) -- that means: no cheaper price for this position.
intermediate result (SELECT * no WHERE) would look like (shortened):
| l.id | l.name | l.product_id | l.price | r.id | r.name | r.product_id | r.price
| 3 | phone | 11 | 380 | null | null | null | null
| 4 | phone | 11 | 460 | 3 | phone | 3 | 380
Side node: For very large datasets there might be performance-issues, because every additional line of a component would add multiple result rows. i.e. consider another phone:
| l.id | l.name | l.product_id | l.price | r.id | r.name | r.product_id | r.price
| 3 | phone | 11 | 380 | null | null | null | null
| 4 | phone | 11 | 460 | 3 | phone | 3 | 380
| 5 | phone | 11 | 500 | 3 | phone | 3 | 380
| 5 | phone | 11 | 500 | 4 | phone | 3 | 460
So, if you want to get the lowest price in the past 60 days with daily changes, that will be a huge amount of rows just for "that"... (Actually 60+59+58+...+2+1 I think, cause the most expensive price will produce 59 comparision rows and so on)

MySQL SELECT to VIEW returns different results

I have put together a small sql query which brings data from one table and sorts it under new column names. The sql looks like this:
SELECT course_id AS course, NOW() as datum,
(SELECT COUNT(*) FROM users_courses WHERE course_id = course) AS antal_registrerade,
(SELECT COUNT(*) FROM users_courses WHERE status = 1 AND course_id = course) AS antal_aktiva,
(SELECT COUNT(*) FROM users_courses WHERE status = 3 AND course_id = course) AS antal_avklarade
FROM users_courses GROUP BY course_id
The above query returns the following:
| course | datum | antal_registrerade | antal_aktiva | antal_avklarade |
-----------------------------------------------------------------------------------------
| 31 | 2016-01-12 16:24:58 | 142 | 19 | 83 |
| 38 | 2016-01-12 16:24:58 | 826 | 45 | 49 |
| 39 | 2016-01-12 16:24:58 | 2 | 2 | NULL |
| 43 | 2016-01-12 16:24:58 | 169 | 29 | 32 |
| 44 | 2016-01-12 16:24:58 | 11 | 4 | 2 |
| 45 | 2016-01-12 16:24:58 | 67 | 8 | 7 |
| 46 | 2016-01-12 16:24:58 | 2 | 1 | 1 |
All good right? Just like I wanted it. BUT when I save this query as a view and run that the result is different. I get the same data for every row, except for the course and datum columns.
| course | datum | antal_registrerade | antal_aktiva | antal_avklarade |
-----------------------------------------------------------------------------------------
| 31 | 2016-01-12 16:24:58 | 1219 | 108 | 174 |
| 38 | 2016-01-12 16:24:58 | 1219 | 108 | 174 |
| 39 | 2016-01-12 16:24:58 | 1219 | 108 | 174 |
| 43 | 2016-01-12 16:24:58 | 1219 | 108 | 174 |
| 44 | 2016-01-12 16:24:58 | 1219 | 108 | 174 |
| 45 | 2016-01-12 16:24:58 | 1219 | 108 | 174 |
| 46 | 2016-01-12 16:24:58 | 1219 | 108 | 174 |
Anyone have any idea why this is? The sql found in the saved view looks like this:
SELECT `database`.`users_courses`.`course_id` AS `course`,now() AS `datum`,
(SELECT COUNT(0) from `database`.`users_courses` where (`database`.`users_courses`.`course_id` = `database`.`users_courses`.`course_id`)) AS `antal_registrerade`,
(SELECT COUNT(0) from `database`.`users_courses` where ((`database`.`users_courses`.`status` = 1) and (`database`.`users_courses`.`course_id` = `database`.`users_courses`.`course_id`))) AS `antal_aktiva`,
(SELECT COUNT(0) from `database`.`users_courses` where ((`database`.`users_courses`.`status` = 3) and (`database`.`users_courses`.`course_id` = `database`.`users_courses`.`course_id`))) AS `antal_avklarade`
FROM `database`.`users_courses`
GROUP BY `database`.`users_courses`.`course_id`
This is much simpler to express using conditional aggregation:
SELECT course_id AS course, NOW() as datum,
COUNT(*) as antal_registrerade,
SUM(status = 1) as antal_aktiva,
SUM(status = 3) AS antal_avklarade
FROM users_courses
GROUP BY course_id;
This should fix the problem with your results.
For some reason, the saved code for the view has the correlation clause incorrect. My guess is that you don't have two columns in the table for course and course_id, so your first query isn't exactly what is going into the view. In any case, fix this using a simpler query.