У меня есть этот запрос:
WITH product_grouped AS (
SELECT
p.uniqueid,
cost,
case WHEN cost <= 10 THEN '0-10'
WHEN cost > 10 AND cost <= 25 THEN '10 < Price <= 25'
WHEN cost >= 25 and cost <= 100 THEN '25 < Price <= 100'
ELSE 'Price > 100' end AS price_group
FROM mmc..product p
),
quarters_grouped AS (
SELECT
uniqueid,
unitprice,
quantity,
cart_orderdate,
case WHEN c.cart_orderdate >= DATEADD(QUARTER, -1, getdate()) THEN 'Q1'
WHEN c.cart_orderdate >= DATEADD(QUARTER, -2, getdate()) and c.cart_orderdate < DATEADD(QUARTER, -1, getdate())THEN 'Q2'
WHEN c.cart_orderdate >= DATEADD(QUARTER, -3, getdate()) and c.cart_orderdate < DATEADD(QUARTER, -2, getdate())THEN 'Q3'
WHEN c.cart_orderdate >= DATEADD(QUARTER, -4, getdate()) and c.cart_orderdate < DATEADD(QUARTER, -3, getdate())THEN 'Q4'
WHEN c.cart_orderdate >= DATEADD(QUARTER, -5, getdate()) and c.cart_orderdate < DATEADD(QUARTER, -4, getdate())THEN 'Q5'
WHEN c.cart_orderdate >= DATEADD(QUARTER, -6, getdate()) and c.cart_orderdate < DATEADD(QUARTER, -5, getdate())THEN 'Q6'
WHEN c.cart_orderdate >= DATEADD(QUARTER, -7, getdate()) and c.cart_orderdate < DATEADD(QUARTER, -6, getdate())THEN 'Q7'
WHEN c.cart_orderdate >= DATEADD(QUARTER, -8, getdate()) and c.cart_orderdate < DATEADD(QUARTER, -7, getdate())THEN 'Q8'
end AS quarters
FROM omc..cart c
WHERE c.cart_orderdate > '2018-01-01'
),
sum_by_quarter AS (
SELECT pg.uniqueid, price_group, quarters, SUM(unitprice * quantity) AS total_sold
FROM product_grouped pg
INNER JOIN quarters_grouped qg
ON pg.uniqueid = qg.uniqueid
GROUP BY pg.uniqueid, price_group, quarters
),
partition_five AS (
SELECT quarters, price_group, uniqueid, total_sold, ROW_NUMBER() OVER (PARTITION BY quarters, price_group ORDER BY total_sold DESC) AS RowNo
FROM sum_by_quarter
)
SELECT *
FROM partition_five
WHERE RowNo <= 5
ORDER BY quarters, price_group, total_sold desc
Я хочу знать 5 лучших идентификаторов продаваемых продуктов для продуктов в разных ценовых диапазонах за последние 8 кварталов. Где топ продаж определяется как unitprice * quantity
из таблицы корзины. Диапазон цен Cost <= $10, 10 < Cost <= 25, 25 < Cost <= 100, Cost < 100
. Мой запрос дает мне то, что я хочу, но есть ли более простой способ сделать это без всех инструкций case?