Y
Y
Yuri Velmesov2018-03-23 16:47:36
MySQL
Yuri Velmesov, 2018-03-23 16:47:36

How to compose Mysql query with grouping and cell sums in WHERE clause?

Please tell me how to correctly compose a Mysql query, I'm not good at compound queries.
I have a request

SELECT `products`.`name`          AS `name`,
       SUM(`part`.`rest`)         AS `rest`, -- остаток
       SUM(`part`.`reserve`)      AS `reserve`, -- резерв
       `part`.`revision_actually` AS `rev_actually`, -- актуальный остаток (в админке менеджеры указывают)
       `part`.`code`              AS `code`, -- код товара
       `part`.`point_id`          AS `point_id` -- точка (магазин) к которой привязана партия
FROM `products` -- товары
INNER JOIN `part` -- партии
ON `products`.`id` = `part`.`prod_id`
WHERE `part`.`point_id` IN(1,2) AND (`part`.`rest` + `part`.`reserve`) != `part`.`revision_actually`
GROUP BY `part`.`code`, `part`.`point_id`
ORDER BY `part`.`code` ASC

This query works for me, but does not consider the amount of the balance and the reserve of all parties.
I have a table of products "products" and a table of batches "part" linked to these products by "prod_id"
A product can have any number of batches.
Lots may differ in supplier, prices, and other attributes.
Purpose: Get all batches grouped by code and point of sale, but select only batches that have: the sum of the
balance + the sum of the balance in the reserve is not equal (!=) to the current balance I am substituting the SUM aggregate function into the WHERE condition (error No. 1111)

SELECT `products`.`name`          AS `name`,
       SUM(`part`.`rest`)         AS `rest`, -- остаток
       SUM(`part`.`reserve`)      AS `reserve`, -- резерв
       `part`.`revision_actually` AS `rev_actually`, -- актуальный остаток (в админке менеджеры указывают)
       `part`.`code`              AS `code`, -- код товара
       `part`.`point_id`          AS `point_id` -- точка (магазин) к которой привязана партия
FROM `products` -- товары
INNER JOIN `part` -- партии
ON `products`.`id` = `part`.`prod_id`
WHERE `part`.`point_id` IN(1,2) AND (SUM(`part`.`rest`) + SUM(`part`.`reserve`)) != `part`.`revision_actually`
GROUP BY `part`.`code`, `part`.`point_id`
ORDER BY `part`.`code` ASC

I ask the help of magicians on complex requests!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lazy @BojackHorseman MySQL, 2018-03-23
Tag

HAVING
in where you specify the conditions that apply to data before grouping, in having - after grouping

I
Ivashka69, 2018-03-23
@Ivashka69

Oh you lace, okay don't thank google.com

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question