Subject Re: SQL - Most recent order for each product
Author Svein Erling Tysvær
> This looks good to me, but I'm having trouble getting it to run. The
> complaint is "Invalid expression in the select list(not contained in
> either an aggregate function or GROUP BY clause)"
>
> Usually I can easily fix this type of error. Here I'm having
> trouble. What do I need in the GROUP BY to make it work?

Sorry, I forgot that only aggregate functions can be used without
being in the GROUP BY clause. If you are on Fb 1.5, then try

GROUP BY P.PRODUCT_ID, 3

which I think should work, but I'm only on Fb 1.0.3 myself and there
grouping by ordinal number does not work.

For the stored procedure, it would be something like:

CREATE PROCEDURE CUSTOMERLATESTMAXPRICE
(CUSTOMER_ID INTEGER)
RETURNS
(PRODUCT_ID INTEGER,
MAX_DATE DATE,
MAX_PRICE DECIMAL(9,2))
AS BEGIN
FOR SELECT P.PRODUCT_ID, MAX(O.ORDER_DATE)
FROM PRODUCTS P
JOIN ORDER_ITEMS I
ON P.PRODUCT_ID = I.PRODUCT_ID
JOIN ORDERS O
ON I.ORDER_ID = O.ORDER_ID
WHERE
O.CUSTOMER_ID = :CUSTOMER_ID
GROUP BY P.PRODUCT_ID
INTO :PRODUCT_ID, :MAX_DATE
DO
BEGIN
FOR (SELECT MAX(I.PRICE)
FROM ORDER_ITEMS I
JOIN ORDERS O
ON I.ORDER_ID = O.ORDER_ID
WHERE P.PRODUCT_ID = :PRODUCT_ID
AND O.CUSTOMER_ID = :CUSTOMER_ID
AND O.ORDER_DATE = :MAX_DATE
INTO :MAX_PRICE
DO
BEGIN
SUSPEND;
END
END

and then you would do

SELECT PRODUCT_ID, MAX_DATE, MAX_PRICE
FROM CUSTOMERLATESTMAXPRICE(10300)

Though I hardly ever write stored procedures, so this is likely to
contain errors. Also, note that I removed the table CUSTOMER from the
equation, since you do not use the table for anything and links on the
very same field to ORDERS, I figured it wasn't needed here.

HTH,
Set