使用下面定义的FACT_SALES
和DIM_SELLERS
表,我需要一个查询,该查询仅返回每个年龄段内过去十二个月收入最高的卖家(<30天,31-90天,91-120天,> 120天)。
Age = elapsed time to - date since seller start day
表FACT_SALES
dim_seller_sk BIGINT,
sale_day DATE,
net_units INT,
total_sales_revenue FLOAT
表DIM_SELLERS
dim_seller_sk BIGINT,
seller_name VARCHAR(250),
seller_start_day DATE`
我正在尝试达到这样的年龄:
WITH ages AS
(
SELECT
seller_name,
ROUND(DATEDIFF(day, GETDATE(), seller_start_day), 0) AS age
FROM
dbo.dim_sellers
),
cte2 AS
(
SELECT
ages.seller_name,
CASE
WHEN ages.age <= 30 THEN '<= 30 days'
WHEN ages.age >= 31 AND ages.age <= 90 THEN '31-90 days'
WHEN ages.age >= 91 AND ages.age <= 120 THEN '91-120 days'
WHEN ages.age >= 120 THEN '> 120 days'
END AS age_category
FROM
ages
)
SELECT
'revenue logic',
cte2.seller_name,
cte2.age_category
FROM
dbo.FACT_SALES, cte2
GROUP BY
cte2.seller_name, cte2.age_category
如何计算此收入?正如我得到的age_category
。
我可以在单个select语句中从表和cte中进行选择吗?
难题的一部分是收益逻辑。我可以得到一些有关如何实现该目标的提示。
答案 0 :(得分:1)
您只需要一个合适的JOIN
吗?
with ages as (
select s.*,
ROUND(DATEDIFF(day, getdate(),seller_start_day), 0) as age
from dbo.dim_sellers s
),
cte2 as (
select ages.*,
(case when ages.age <= 30 then '<=30 days'
when ages.age <= 90 then '31-90 days'
when ages.age <= 120 then '91-120 days'
else '>120 days'
end
) as age_category
from ages
)
select 'revenue logic', cte2.seller_name, cte2.age_category,
sum(s.total_sales_revenue)
from dbo.FACT_SALES s join
cte2
on cte2.dim_seller_sk = s.dim_seller_sk
where s.sale_day >= dateadd(month, -12, getdate())
group by cte2.seller_name, cte2.age_category;