Reputation: 544
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))
Upvotes: 0
Views: 1916
Reputation: 544
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 . '"
Upvotes: 0
Reputation: 1269873
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.
Upvotes: 1