[英]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".
我有 2 个表“facture”和“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
:我建议
JOIN
和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 . '"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.