К сожалению, SQL Server (пока?) Не поддерживает «первую» и «последнюю» функции как функции агрегирования. Он поддерживает их как оконные функции, поэтому вы можете сделать:
select distinct customer_id,
first_value(product_id) over (partition by customer_id order by order_date asc) as first_product,
first_value(product_id) over (partition by customer_id order by order_date desc) as last_product
from orders o
where exists (select 1
from orders o2
where o2.customer_id = o.customer_id and
o2.order_date <> o.order_date
);
Или, если вам нравятся оконные функции, вы можете обойтись без select distinct
и exists
:
select customer_id, first_product, last_product
from (select o.*,
first_value(product_id) over (partition by customer_id order by order_date asc) as first_product,
first_value(product_id) over (partition by customer_id order by order_date desc) as last_product,
count(*) over (partition by customer_id) as cnt,
row_number() over (partition by customer_id order by order_date) as seqnum
) o
where cnt >= 2 and seqnum = 1;
Я бы сформулировал условную агрегацию следующим образом:
select o.customer_id,
max(case when seqnum_asc = 1 then o.product_id end) as first_product,
max(case when seqnum_desc = 1 then o.product_id end) as last_product
from (select o.*,
row_number() over (partition by customer_id order by order_date asc) as seqnum_asc,
row_number() over (partition by customer_id order by order_date desc) as seqnum_desc
from orders o
) o
group by customer_id
having count(*) >= 2;
Традиционный метод неоконной функции будет использовать два соединения:
select o.customer_id,
firsto.product_id as first_product,
lasto.product_id as last_product
from (select customer_id, min(order_date) as min_od,
max(order_date) as max_od
from orders o
group by customer_id
having count(*) >= 2
) o join
orders firsto
on firsto.customer_id = o.customer_id and
firsto.order_date = o.min_od join
orders lasto
on lasto.customer_id = o.customer_id and
last.order_date = o.max_od;
На самом деле это наиболее удобный способ, если вы хотите получить несколько значений для каждого заказа - скажем, сумму, способ оплаты и дату в дополнение к товару.