更新select查询中的列值

wfveoks0  于 2021-06-26  发布在  Impala
关注(0)|答案(3)|浏览(360)

我有一个复杂的sql问题。
我们可以在select查询中更新列吗?例子:
考虑下这张表:

  1. |ID |SeenAt |
  2. ----------------
  3. |1 |20 |
  4. |1 |21 |
  5. |1 |22 |
  6. |2 |70 |
  7. |2 |80 |

我想要一个select查询,它给出每个id第一次出现的时间。什么时候又看到了

  1. |ID |Start |End |
  2. ---------------------
  3. |1 |20 |21 |
  4. |1 |20 |22 |
  5. |1 |20 |22 |
  6. |2 |70 |80 |
  7. |2 |70 |80 |

首先,两列 Start 以及 End 将具有相同的值,但当第二行具有相同的 ID 我们需要更新它的前身 End 新的 SeenAt 价值观。我成功地创造了 Start 列,我给出最小值 SeenAt 每小时价值 ID 所有ID。但我找不到办法更新 End 每次都是列。
别介意双倍,我还有其他列,每一行都会改变
此外,我在 Impala 工作,但我可以使用甲骨文。
我希望我已经说得够清楚了。谢谢您

tkclm6bt

tkclm6bt1#

你似乎需要 min() 解析函数 self-join :

  1. select distinct t1.ID,
  2. min(t1.SeenAt) over (partition by t1.ID order by t1.ID) as "Start",
  3. t2.SeenAt as "End"
  4. from tab t1
  5. join tab t2 on t1.ID=t2.ID and t1.SeenAt<=t2.SeenAt
  6. order by t2.SeenAt;

演示

w6mmgewl

w6mmgewl2#

你可以用 lead() 以及 nvl() :

  1. select id, min(seenat) over (partition by id) seen_start,
  2. nvl(lead(seenat) over (partition by id order by seenat), seenat) seen_end
  3. from t

演示

xyhw6mcr

xyhw6mcr3#

开始很容易 MINGROUP 结束后你需要找到最小值 SeenAt 如果你找不到,那么电流 SeenAt sql演示

  1. SELECT "ID",
  2. (SELECT MIN("SeenAt")
  3. FROM Table1 t2
  4. WHERE t1."ID" = t2."ID") as "Start",
  5. COALESCE(
  6. (SELECT MIN("SeenAt")
  7. FROM Table1 t2
  8. WHERE t1."ID" = t2."ID"
  9. AND t1."SeenAt" < t2."SeenAt")
  10. , t1."SeenAt"
  11. ) as End
  12. FROM Table1 t1

输出

  1. | ID | START | END |
  2. |----|-------|-----|
  3. | 1 | 20 | 21 |
  4. | 1 | 20 | 22 |
  5. | 1 | 20 | 22 |
  6. | 2 | 70 | 80 |
  7. | 2 | 70 | 80 |
展开查看全部

相关问题