Subject (Repost) Problem with SUM() on a computed column
Author joenyang
Hi all,

I have a master (X) and a detail (Y) table.
Table X contains a timestamp and the sum of
the amounts of its details. Table Y on the
other hand, contains detail information such
as description, quantity, unit price, amount
and the ISRETURNED column, which indicates
whether this item is returned (1) or not (0).
All amounts are positive values.

Now, the AMOUNT fiels of table X is computed
by subtracting all detail records where
ISRETURNED = 1 from detail records having
ISRETURNED = 0.

Using the script at the bottom of this message,
I executed the ff. query:

SELECT * FROM X;

and yielded...

1/1/2003 3323.75
2/1/2003 1441.75
3/1/2003 379

...which is correct. But when I queried the
SUM() of the AMOUNT column:

SELECT SUM(AMOUNT) FROM X;

I got 9971.25 instead of 5144.5.

Computed fields with simple SUM() selects are
OK, only selects like the AMOUNT column in
table X.

Anything wrong with my script?

Thanks :)

SQL script follows:

CREATE TABLE X
(
DATETIME TIMESTAMP NOT NULL,
PRIMARY KEY (DATETIME)
);

CREATE TABLE Y
(
DATETIME TIMESTAMP NOT NULL,
DESCRIPTION VARCHAR(20) NOT NULL,
QUANTITY INTEGER NOT NULL,
UNITPRICE NUMERIC(15, 2) NOT NULL,
AMOUNT COMPUTED BY (QUANTITY * UNITPRICE),
ISRETURNED SMALLINT DEFAULT 0 NOT NULL,
PRIMARY KEY (DATETIME, DESCRIPTION)
);

ALTER TABLE Y
ADD CONSTRAINT Y_X
FOREIGN KEY (DATETIME)
REFERENCES X (DATETIME)
ON UPDATE CASCADE
ON DELETE CASCADE;

ALTER TABLE X
ADD AMOUNT COMPUTED BY
((SELECT (SELECT COALESCE(SUM(AMOUNT), 0)
FROM Y
WHERE DATETIME = X.DATETIME AND
ISRETURNED = 0) -
(SELECT COALESCE(SUM(AMOUNT), 0)
FROM Y
WHERE DATETIME = X.DATETIME AND
ISRETURNED <> 0)
FROM RDB$DATABASE));

INSERT INTO X (DATETIME) VALUES ('1/1/2003');
INSERT INTO X (DATETIME) VALUES ('2/1/2003');
INSERT INTO X (DATETIME) VALUES ('3/1/2003');

INSERT INTO Y (DATETIME, DESCRIPTION, QUANTITY, UNITPRICE, ISRETURNED)
VALUES ('1/1/2003', 'PANTS', 5, 564.75, 0);
INSERT INTO Y (DATETIME, DESCRIPTION, QUANTITY, UNITPRICE, ISRETURNED)
VALUES ('1/1/2003', 'T-SHIRT', 2, 250.00, 0);

INSERT INTO Y (DATETIME, DESCRIPTION, QUANTITY, UNITPRICE, ISRETURNED)
VALUES ('2/1/2003', 'BLOUSE', 1, 290.25, 1);
INSERT INTO Y (DATETIME, DESCRIPTION, QUANTITY, UNITPRICE, ISRETURNED)
VALUES ('2/1/2003', 'SOCKS', 12, 123.5, 0);
INSERT INTO Y (DATETIME, DESCRIPTION, QUANTITY, UNITPRICE, ISRETURNED)
VALUES ('2/1/2003', 'T-SHIRT', 1, 250, 0);

INSERT INTO Y (DATETIME, DESCRIPTION, QUANTITY, UNITPRICE, ISRETURNED)
VALUES ('3/1/2003', 'POLO', 2, 189.5, 0);