SQL - 如何判断列的组合是否出现过?
SQL - How to find if the combination of column has occured before or not?
下面的例子演示了问题
id
位置
dt
1
印度
2020-01-01
2
美国
2020-02-01
1
美国
2020-03-01
3
中国
2020-04-01
1
印度
2020-05-01
2
法国
2020-06-01
1
印度
2020-07-01
2
美国
2020-08-01
此 table 按日期排序。
我想创建另一个列,它会告诉 id 是否已经到过该位置。
所以,输出就像
id
位置
dt
去过
1
印度
2020-01-01
0
2
美国
2020-02-01
0
1
美国
2020-03-01
0
3
中国
2020-04-01
0
1
印度
2020-05-01
1
2
法国。
2020-06-01
0
1
印度
2020-07-01
1
2
美国
2020-08-01
1
我面临的问题是,对于每一行,我只需要考虑它上面的行。
在 CASE
表达式中使用 EXISTS
:
SELECT t1.id, t1.location,
CASE
WHEN EXISTS (
SELECT 1
FROM tablename t2
WHERE t2.id = t1.id AND t2.location = t1.location AND t2.date < t1.date
) THEN 1
ELSE 0
END travelled
FROM tablename t1
为此我强烈推荐 window 函数:
select t.*,
(case when row_number() over (partition by id, location order by date) > 1
then 1 else 0
end) as travelled
from t;
Window 函数通常比其他方法更快。
下面的例子演示了问题
id | 位置 | dt |
---|---|---|
1 | 印度 | 2020-01-01 |
2 | 美国 | 2020-02-01 |
1 | 美国 | 2020-03-01 |
3 | 中国 | 2020-04-01 |
1 | 印度 | 2020-05-01 |
2 | 法国 | 2020-06-01 |
1 | 印度 | 2020-07-01 |
2 | 美国 | 2020-08-01 |
此 table 按日期排序。 我想创建另一个列,它会告诉 id 是否已经到过该位置。
所以,输出就像
id | 位置 | dt | 去过 |
---|---|---|---|
1 | 印度 | 2020-01-01 | 0 |
2 | 美国 | 2020-02-01 | 0 |
1 | 美国 | 2020-03-01 | 0 |
3 | 中国 | 2020-04-01 | 0 |
1 | 印度 | 2020-05-01 | 1 |
2 | 法国。 | 2020-06-01 | 0 |
1 | 印度 | 2020-07-01 | 1 |
2 | 美国 | 2020-08-01 | 1 |
我面临的问题是,对于每一行,我只需要考虑它上面的行。
在 CASE
表达式中使用 EXISTS
:
SELECT t1.id, t1.location,
CASE
WHEN EXISTS (
SELECT 1
FROM tablename t2
WHERE t2.id = t1.id AND t2.location = t1.location AND t2.date < t1.date
) THEN 1
ELSE 0
END travelled
FROM tablename t1
为此我强烈推荐 window 函数:
select t.*,
(case when row_number() over (partition by id, location order by date) > 1
then 1 else 0
end) as travelled
from t;
Window 函数通常比其他方法更快。