0

我需要从一列的行值派生列。

这是行数据。

CustomerID  Activity    Date
10001       Active      2018-06-21
10001       Inactive    2018-06-25
10001       Active      2018-08-22
10001       Inactive    2018-10-06

这是我想要得到的输出:

CustomerID  ActiveDate      InactiveDate
10001       2018-06-21      2018-06-25
10001       2018-08-22      2018-10-06

请帮忙!谢谢!

4

2 回答 2

1

您可以尝试在子查询中创建行号group by CustomerID,Activity,然后执行条件聚合函数。

SELECT CustomerID,
       MAX(CASE WHEN Activity = 'Active' THEN Date END) ActiveDate,
       MAX(CASE WHEN Activity = 'Inactive' THEN Date END) InactiveDate
FROM (
    SELECT *,ROW_NUMBER() OVER(PARTITION BY CustomerID,Activity ORDER BY Date ) rn
    FROM T
)t1
group by CustomerID,rn

sqlfiddle

于 2018-11-10T00:50:55.830 回答
0

你的逻辑有点不清楚。如果您想要下一个“非活动”日期:

select CustomerID, date as active_date, inactive_date
from (select t.*,
             min(case when activity = 'Inactive' then date end) over (partition by CustomerID order by date desc) as inactive_date
      from t
     ) t
where activity = 'Active';
于 2018-11-10T13:03:47.010 回答