I have three (3) tables which l want to get the sum total of amount from it.
OrderDetail
| Product | Amount | OrderDate |
|---|---|---|
| Apple | 10 | 2023-09-01 |
| Orange | 5 | 2023-10-01 |
LearnerDetail
| Name | Amount | OrderDate |
|---|---|---|
| Tutor | 30 | 2023-09-01 |
| Levy | 10 | 2023-09-01 |
StoreDetail
| Name | Amount | OrderDate |
|---|---|---|
| Loc A | 5 | 2023-09-01 |
| Loc B | 5 | 2023-10-01 |
This is what I've tried.
SELECT
DATEPART(m, orderdate) AS Month,
Total = (SELECT SUM(amount)
FROM orderdetail) +
(SELECT SUM(amount)
FROM learnerdetail) +
(SELECT SUM(amount)
FROM storedetail)
GROUP BY
DATEPART(m, orderdate)
Expected output
| OrderDate | Total |
|---|---|
| 2023-09-01 | 55 |
| 2023-10-01 | 10 |
One possible solution involves leveraging the
WITHclause to create a temporary table that unifies the desired data from various sources(Common Table Expression). Subsequently, we employ theSELECTstatement with theGROUP BYclause to obtain the desired aggregate values.Here you can use
GROUP BY EOMONTH(order_date)which is probably better, especially if you have more than 12 months of data.