My table structure is following :
CREATE TABLE `tbl_erp_invoice_lines` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`INVOICE_ID` INT(11) NULL DEFAULT NULL,
`PRODUCT_ID` INT(11) NULL DEFAULT NULL,
`LINE_UNIT` VARCHAR(10) NULL DEFAULT 'KG' COLLATE 'utf8_bin',
`LINE_PRICE` DECIMAL(7,3) NULL DEFAULT NULL,
`LINE_QUANTITY` INT(11) NULL DEFAULT NULL,
`LINE_VAT` INT(11) NULL DEFAULT '18',
`LINE_MARK` INT(11) NULL DEFAULT NULL,
`CREATEDON` DATETIME NULL DEFAULT current_timestamp(),
`CREATEDBY` INT(11) NULL DEFAULT '1',
`LASTUPDATEON` DATETIME NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`LASTUPDATEBY` INT(11) NULL DEFAULT '1',
)
LINE_MARK is always -1 or 1
In this table there may be several records with same PRODUCT_IDs. And those records may have a LINE_MARK -1 or 1
Now I want to SUM(LINE_PRICE*LINE_QUANTITY*LINE_MARK)
for the PRODUCT_IDs which has at least one LINE_MARK=-1
in the table. If there isnt then records with this PRODUCT_ID will be excluded from SUM()
select SUM(LINE_PRICE*LINE_QUANTITY*LINE_MARK) from tbl_erp_invoice_lines
where LINE_MARK=-1
doesn’t work because in this case every record with LINE_MARK=1 will be excluded which I don’t want
Thanks!
3
Answers
I tried to solve this question with the help of artificial intelligence. First, I consulted Bard. Despite many attempts, Bard was unable to find the correct answer. On the other hand, ChatGPT gave the correct result on its first attempt.
And here is the correct solution
Join with a subquery that finds all the products that have at least one
LINE_MARK=-1
row.I would suggest using exists to check the existence of any valid row: