I have a database consisting of over 1 million orders, I'm looking to select the last order (indicated by OrderDate) for a customer (indicated as CustomerID).

Here's what I've tried so far:

SELECT 
    MAX(ORDERDATE) AS ORDERDATE,
    ORDERID,
    ORDERITEMID,
    ITEMID,
    MENUITEMNAME,
    ITEMSIZE,
    CUSTOMERID,
    ORDERDATETIME,
    APPNAME,
    UNITID,
    UNIT_NAME,
    UNIT_DETAIL_NAME,
    SECTOR,
    STOREID,
    STORENAME,
    ADDRESS_COUNTRY,
    TRANSACTIONTYPEREFID,
    BRANDNAME,
    PAYMENTTYPE,
    VOLANTETRANSACTIONID,
    PROMOTIONCODE,
    DISCOUNTAMOUNT,
    DISCOUNT_VALUEISAMOUNT,
    QUANTITY,
    SALES,
    PRICECURRENCYCODE,
    LIVE,
    TIMEZONE,
    LOAD_DATE 
FROM CDL_DH_DATAMART
GROUP BY  
    ORDERID,
    ORDERITEMID,
    ITEMID,
    MENUITEMNAME,
    ITEMSIZE,
    CUSTOMERID,
    ORDERDATETIME,
    APPNAME,
    UNITID,
    UNIT_NAME,
    UNIT_DETAIL_NAME,
    SECTOR,
    STOREID,
    STORENAME,
    ADDRESS_COUNTRY,
    TRANSACTIONTYPEREFID,
    BRANDNAME,
    PAYMENTTYPE,
    VOLANTETRANSACTIONID,
    PROMOTIONCODE,
    DISCOUNTAMOUNT,
    DISCOUNT_VALUEISAMOUNT,
    QUANTITY,
    SALES,
    PRICECURRENCYCODE,
    LIVE,
    TIMEZONE,
    LOAD_DATE
up vote 1 down vote accepted

Give this a try.

You want to partition and sort your result to get the first record.

SELECT 

    ORDERDATE, 
    ORDERID, 
    ORDERITEMID, 
    ITEMID,
    MENUITEMNAME, 
    ITEMSIZE, 
    CUSTOMERID, 
    ORDERDATETIME, 
    APPNAME, 
    UNITID, 
    UNIT_NAME, 
    UNIT_DETAIL_NAME,
    SECTOR, 
    STOREID, 
    STORENAME, 
    ADDRESS_COUNTRY,
    TRANSACTIONTYPEREFID,
    BRANDNAME, 
    PAYMENTTYPE, 
    VOLANTETRANSACTIONID,
    PROMOTIONCODE, 
    DISCOUNTAMOUNT,
    DISCOUNT_VALUEISAMOUNT, 
    QUANTITY, 
    SALES, 
    PRICECURRENCYCODE, 
    LIVE, 
    TIMEZONE, 
    LOAD_DATE 

From (

    Select
        ORDERDATE, 
        ORDERID, 
        ORDERITEMID, 
        ITEMID,
        MENUITEMNAME, 
        ITEMSIZE, 
        CUSTOMERID, 
        ORDERDATETIME, 
        APPNAME, 
        UNITID, 
        UNIT_NAME, 
        UNIT_DETAIL_NAME,
        SECTOR, 
        STOREID, 
        STORENAME, 
        ADDRESS_COUNTRY,
        TRANSACTIONTYPEREFID,
        BRANDNAME, 
        PAYMENTTYPE, 
        VOLANTETRANSACTIONID,
        PROMOTIONCODE, 
        DISCOUNTAMOUNT,
        DISCOUNT_VALUEISAMOUNT, 
        QUANTITY, 
        SALES, 
        PRICECURRENCYCODE, 
        LIVE, 
        TIMEZONE, 
        LOAD_DATE,
        ROW_NUMBER() OVER (PARTITION BY CUSTOMERID ORDER BY ORDERDATE DESC) as ID_Row 
    FROM CDL_DH_DATAMART 

) as A 
WHERE ID_Row = 1

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.