在mysql

时间:2018-02-23 10:46:07

标签: mysql sql

我有一个名为'T1'的表,我想要转置并有date_from和date_to列。该表本身具有谁是特定公司的经理的数据。所以我想知道自何时用户负责公司。我可以使用以下查询在BigQuery中轻松完成,但我很难在MySQL中做同样的事情。

WITH T1 AS (  SELECT  9 as rating, 'company1' as cid, 100 as user, '2017-08-20' AS created UNION ALL
          SELECT  9 as rating, 'company1' as cid, 101 as user, '2017-08-22' AS created UNION ALL
          SELECT 10 as rating, 'company1' as cid, 101 as user, '2017-08-21' AS created

        )

    SELECT cid, rating, user, CAST(created as DATE) as date_from,
          CAST(COALESCE(MIN(CAST(created as DATE)) OVER(PARTITION BY cid, rating ORDER BY CAST(created as DATE) DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING),
          DATE_ADD(current_date(), INTERVAL 1 DAY)) as DATE) AS date_to
         FROM T1

原始表格格式:

rating  cid user    created  
9   company1    100 2017-08-20   
9   company1    101 2017-08-22   
10  company1    101 2017-08-21

决赛桌应具有以下格式:

cid rating  user    date_from   date_to  
1   company1    9   101 2017-08-22  2018-02-24   
2   company1    9   100 2017-08-20  2017-08-22   
3   company1    10  101 2017-08-21  2018-02-24

谢谢!

1 个答案:

答案 0 :(得分:2)

您确实需要lead(),这在MySQL中不可用(并且会使BigQuery查询更简单)。一种方法使用相关子查询:

select t1.*, t1.created as date_from,
       (select min(tt1.created)
        from t1 tt1
        where tt1.cid = t1.cid and tt1.created > t1.created
       ) as date_to
from t1;