DECLARE @Sample TABLE (Acct INT, Item VARCHAR(10), [Desc] VARCHAR(10), SaleDate DATETIME, Cost MONEY)
INSERT @Sample
SELECT 1, 'soap', 'bar', '10.01.07', 1.23 UNION ALL
SELECT 1, 'soap', 'bar', '10.05.07', 12.39 UNION ALL
SELECT 1, 'soap', 'bar', '10.31.07', 3.28
;WITH Yak (Acct, [1st date], [Last date], MinCost, MaxCost)
AS (
SELECT Acct,
MAX(CASE WHEN a = 1 THEN SaleDate ELSE NULL END),
MAX(CASE WHEN b = 1 THEN SaleDate ELSE NULL END),
MAX(CASE WHEN a = 1 THEN Cost ELSE NULL END),
MAX(CASE WHEN b = 1 THEN Cost ELSE NULL END)
FROM (
SELECT Acct,
SaleDate,
Cost,
ROW_NUMBER() OVER (PARTITION BY Acct ORDER BY SaleDate) AS a,
ROW_NUMBER() OVER (PARTITION BY Acct ORDER BY SaleDate DESC) AS b
FROM @Sample
) AS d
WHERE 1 IN (a, b)
GROUP BY Acct
)
SELECT Acct,
[1st date],
[Last date],
MinCost,
MaxCost
FROM Yak
WHERE MinCost <> MaxCost
|