如何使用排名多次将表连接到自身?

时间:2017-12-11 10:43:17

标签: sql amazon-redshift

如果有现有解决方案,我道歉,我尝试了相当多的搜索,但找不到多少。

这就是我想要做的事情:

我有一张类似于第一张图片的桌子。我希望它看起来像第二个图像。基本上每次rnk_address = 1,我都希望将该行的order_date移动到相关user_id的单独列中。

我最终试图通过order_date计算所有rnk_address = 1之间user_id的平均差异。

我使用排名添加了user_counter列,因为我想我需要在user_rank = user_rank + 1的某个时间进行加入?但不确定......

原始表:

enter image description here

最终结果:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select 
    l.LocationName, l.LocationPrefixCode, 
    sum(case lt.transid when 1 then lt.Points else 0 end) as TotalEarnpoints, 
    sum(case lt.transid when 2 then lt.points else 0 end) as TotalRedeempoints, 
    sum(case lt.transid when 1 then 1 else 0 end) as NoOfBillsEarned, 
    sum(case lt.transid when 2 then 1 else 0 end) as NoOfBillsRedeemed
from 
    InvLoyaltyTransaction lt 
inner join
    dbo.Location l ON lt.LocationID = l.LocationID 
where 
    cast(DocumentDate as date) between convert(date, '" + fromDate + "', 103)  
                                   and convert(date, '" + toDate + "', 103) 
    and CardType in (select CardMasterID 
                     from CrmReportCondition) 
    and lt.LocationID != 1
group by
    l.LocationName, l.LocationPrefixCode 
order by 
    l.LocationName