# Complex Query SQL

**URL:** <https://discourse.cakephp.org/t/complex-query-sql/10476>\
**Category:** Need Help\
**Tags:** help\
**Created:** [June 24, 2022, 4:12pm UTC](https://discourse.cakephp.org/t/complex-query-sql/10476 "2022-06-24T16:12:11Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![agencep](https://avatars.discourse-cdn.com/v4/letter/a/258eb7/32.png) [@agencep](https://discourse.cakephp.org/u/agencep)\
**Post date:** [June 24, 2022, 4:12pm UTC](https://discourse.cakephp.org/t/complex-query-sql/10476/1 "2022-06-24T16:12:11Z")

</div>

Hi,

Is there a merciful soul who can help me with complex sql queries on CakePHP 4.x?

```auto
"SELECT SUM(a.Qte_In - b.qte_delivred) AS Stock
FROM	(SELECT product_id, SUM(Qte_In) AS Qte_IN FROM besdtls WHERE product_id = 1 GROUP BY product_id) As a
JOIN	(SELECT product_id, SUM(Qte_Delivred) AS Qte_Delivred FROM orderdetails WHERE product_id = 1 GROUP BY product_id) As b ON b.product_id = a.product_id
WHERE	a.product_id = 1";

```

Thanks

---

<div class="post-metadata">

**Author:** ![ndm](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/ndm/32/2234_2.png) [@ndm](https://discourse.cakephp.org/u/ndm)\
**Post date:** [June 25, 2022, 1:00pm UTC](https://discourse.cakephp.org/t/complex-query-sql/10476/2 "2022-06-25T13:00:35Z")

</div>

What exactly is it that you’re struggling with? What have you tried so far?

---

<div class="post-metadata">

**Author:** ![agencep](https://avatars.discourse-cdn.com/v4/letter/a/258eb7/32.png) [@agencep](https://discourse.cakephp.org/u/agencep)\
**Post date:** [June 25, 2022, 1:04pm UTC](https://discourse.cakephp.org/t/complex-query-sql/10476/3 "2022-06-25T13:04:03Z")

</div>

I don’t know how to do it that’s all

I just need to calculate the current stock  
I need to take the sum of qte\_in from the besdtls table  
and i have to take sum of qte\_delivered from orderdetails table

---

<div class="post-metadata">

**Author:** ![ndm](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/ndm/32/2234_2.png) [@ndm](https://discourse.cakephp.org/u/ndm)\
**Post date:** [June 25, 2022, 1:18pm UTC](https://discourse.cakephp.org/t/complex-query-sql/10476/4 "2022-06-25T13:18:42Z")

</div>

You don’t know how to do _what_? Executing raw SQL? Using the query builder? Figuring the correct SQL for whatever you’re trying to do? …?

---

<div class="post-metadata">

**Author:** ![agencep](https://avatars.discourse-cdn.com/v4/letter/a/258eb7/32.png) [@agencep](https://discourse.cakephp.org/u/agencep)\
**Post date:** [June 27, 2022, 8:21am UTC](https://discourse.cakephp.org/t/complex-query-sql/10476/5 "2022-06-27T08:21:33Z")

</div>

that’s what i did in the end
