简体   繁体   中英

Select rows in a table where id is equals to another id in another table and sum values in column from the result

I have a small situation here. I have 2 tables "facture" and "facturedet".

I can get this query working correctly:

SELECT * 
FROM facturedet  
WHERE facture_id IN (SELECT rowid 
                     FROM facture 
                     WHERE CAST(date_valid AS DATE) = current_date)

Now, in the result of the above query, I have a column "qty".

How can I sum the values in this column? I've tried

SELECT SUM(qty) 
FROM
    (SELECT * 
     FROM llx_facturedet 
     WHERE fk_facture IN (SELECT rowid 
                          FROM llx_facture 
                          WHERE CAST(date_valid AS DATE) = current_date))

I would suggest JOIN and GROUP BY :

SELECT SUM(fd.qty)
FROM facturedet fd JOIN
     facture f
     ON fd.facture_id = f.rowid
WHERE date_valid >= current_date AND
      date_valid < current_date INTERVAL '1 DAY';

Note: This uses inequalities for the date comparison. The exact method for adding one date varies by database. In most databases, this structure for the comparison is better for the optimizer, which means a faster query.

This is the final query I am using:

Select
    COALESCE(SUM(CASE WHEN f.type = 2 THEN -fd.qty ELSE fd.qty END), 0) As qty_sum
From
    ' . MAIN_DB_PREFIX . 'facturedet fd 
Inner Join
    ' . MAIN_DB_PREFIX . 'facture f On fd.fk_facture = f.rowid 
Inner Join
    ' . MAIN_DB_PREFIX . 'societe_commerciaux sc On sc.fk_soc = f.fk_soc 
Inner Join
    ' . MAIN_DB_PREFIX . 'user u On sc.fk_user = u.rowid
Where
    f.$this->typeDate Between $this->startDate And $this->endDate 
And
    u.rowid = "' . $this->userId . '"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM