I hace 2 tables
CREATE TABLE SALES (
ID BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
SALE_NUMBER NCHAR VARYING(10) COLLATE ES_ES_CI_AI,
SALE_DATE TIMESTAMP,
AMOUNT DECIMAL(12, 2))
and
CREATE TABLE PAYMENTS (
ID BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
SALE_ID BIGINT,
AMOUNT DECIMAL(12, 2))
SALES table has these values:
1 A01 18/07/2025 12:15 125,30
2 A02 18/07/2025 13:07 50,40
3 A03 19/07/2025 10:05 40,50
PAYMENTS table has these values:
ID SALE_ID AMOUNT
1 2 40,80
2 1 20,50
3 1 25,00
I want a query that obtains the day's sales and the payments that have been made from those sales.
Something like this:
SELECT CAST(S.SALE_DATE AS DATE), SUM(S.AMOUNT) AS SALES_OF_THE_DAY,
COALESCE (SUM (P.AMOUNT), 0) AS DAILY_PAYMENTS
FROM SALES S
LEFT JOIN PAYMENTS P ON (P.SALE_ID=
S.ID)
GROUP BY CAST(S.SALE_DATE AS DATE)
This query works fine until I have more than 1 payment for a sale.
With the data I have indicated, I have these results:
18/07/2025 301,00 86,30
19/07/2025 40,50 0,00
The correct result I'm trying to get is this:
18/07/2025 175,70 86,30
19/07/2025 40,50 0,00
Please, Can someone help me? I'm a little dim today and I can't find a way.
Thank you.