获取以前的不同号码

时间:2017-07-06 09:17:53

标签: sql google-bigquery

我有下表:

    id         date           status
    1        2017-04-20        good
    1        2017-04-19        bad
    1        2017-04-18        bad
    2        2017-04-20        ok
    2        2017-04-19        ok
    2        2017-04-17        ok
    2        2017-04-16        bad

我需要的是获取每个ID 状态列中的先前不同值。

假设今天是2017-04-20,结果将如下所示:

        id       previous_status
        1         bad
        2         bad

之后,我想在案例陈述中使用这些信息: 状态='好'和previous_status ='坏',....

1 个答案:

答案 0 :(得分:0)

根据您的第一个要求,您可以这样做:

SELECT id, status AS previous_status
FROM table_name
WHERE (id, date_col) IN (
        SELECT id, MAX(date_col)
        FROM table_name
        WHERE DATE(date_col) < "2017-04-20"
    );                       

这是针对使用CASE语句的第二个要求

SELECT t.id, t.status, t1.previous_status,
    CASE 
        WHEN t.status = 'good' AND t1.previous_status = 'bad' THEN 'some_value' 
        ELSE 'other_value' 
    END AS case_col
FROM table_name t
INNER JOIN (
    SELECT id, status AS previous_status
    FROM table_name
    WHERE (id, date_col) IN (
            SELECT id, MAX(date_col)
            FROM table_name
            WHERE DATE(date_col) < "2017-04-20"
        )
) t1
ON t.id = t1.id
WHERE DATE(t.date_col) = "2017-04-20";

此引用how_to_compare_date_google_big_query