使用一列的最大值创建新列,在其他列上进行分区和过滤

问题描述 投票:0回答:1

我正在尝试从下面的原始数据生成以下结果集:

原始数据(源表):

Raw Data

期望的结果集:

Results Set

本质上,我希望将 MAX 值按每个 UserID 和 Store 进行分区,并按产品进行过滤,其中一列仅包含 Apple 值,一列仅包含 Grape 值。我能够实现此目的的唯一方法是为每个新列创建单独的 CTE 表,对数据进行分区和筛选,然后将它们连接在一起,但这会导致性能问题。

WITH cte AS
(
       SELECT *
       FROM   SourceTable]), cte2 AS
(
       SELECT *,
              Max([Value]) OVER (partition BY [UserID], [Store]) AS max_value_by_apples
       FROM   cte
       WHERE  [Product] = 'Apples'), cte3 AS
(
       SELECT *,
              Max([Value]) OVER (partition BY [UserID], [Store]) AS max_value_by_grapes
       FROM   cte
       WHERE  [Product] = 'Grapes')
SELECT    a.*,
          b.max_value_by_apples,
          c.max_value_by_grapes
FROM      cte a
LEFT JOIN cte2 b
ON        a.[UserID] = b.[UserID]
AND       a.[Store] = b.[Store]
LEFT JOIN cte3 c
ON        a.[UserID] = c.[UserID]
AND       a.[Store] = c.[Store]

任何帮助将不胜感激。

sql-server t-sql partitioning
1个回答
0
投票
select *
  ,max(case when product='Apples' then value end)over(partition by userid,store) max_value_by_apples
  ,max(case when product='Grapes' then value end)over(partition by userid,store) max_value_by_grapes
from data
© www.soinside.com 2019 - 2024. All rights reserved.