נתונה טבלת הזמנת לקוחות. תחת טבלה זו קיימות העמודות הבאות : מספר לקוח, מספר ספק, מספר הזמנה ותאריך ההזמנה.
CREATE TABLE cust_orders (custid int, supid int, orderid int, orderdate datetime)
צרו שאילתה אשר מציגה שורה אחת עבור כל לקוח, שורה זו תציג את תאריך ההזמנה המאוחר ביותר עבורו. לדוגמא, עבור הטבלה המופיעה מעלה יוחזרו התוצאות הבאות :
CREATE TABLE cust_orders (custid int, supid int, orderid int, orderdate datetime) INSERT INTO cust_orders VALUES (1,1,2,getdate() + 1) INSERT INTO cust_orders VALUES (1,2,3,getdate() + 2) INSERT INTO cust_orders VALUES (1,3,4,getdate() + 3) INSERT INTO cust_orders VALUES (1,4,5,getdate() + 4) INSERT INTO cust_orders VALUES (1,5,6,getdate() + 5) INSERT INTO cust_orders VALUES (1,6,7,getdate() + 6) INSERT INTO cust_orders VALUES (2,1,2,getdate() + 1) INSERT INTO cust_orders VALUES (2,2,3,getdate() + 2) INSERT INTO cust_orders VALUES (2,3,4,getdate() + 3) INSERT INTO cust_orders VALUES (2,4,5,getdate() + 4) INSERT INTO cust_orders VALUES (2,5,6,getdate() + 5) INSERT INTO cust_orders VALUES (2,6,7,getdate() + 6)
SELECT TabA.custid , TabA.supid , TabA.orderid, TabA.orderdate FROM cust_orders TabA JOIN (SELECT MAX(orderdate) AS orderdate , custid FROM cust_orders GROUP BY custid) as tabB ON TabA.custid = tabB.custid AND TabA.orderdate = tabB.orderDate