我的源表Test
包含id
列,目标表testm
由id , col2
组成。请帮助我摆脱这个错误。
test (source)
id
---
10
10
20
20
20
30
30
40
目标
testm
id col2
-- ----
10 1
10 2
20 1
20 2
20 3
30 1
30 2
40 1
查询:
select id, (case id
when 10 then select count(id) from test where id =10
when 20 then select count(id) from test where id =20
when 30 then select count(id) from test where id =30
when 40 then select count(id) from test where id =40
else 0 END ) col2 from test
抛出错误:
缺少表达
答案 0 :(得分:0)
通过查看所需的输出,我猜你想按组对每次出现的id进行编号;如果是这种情况,使用row_number分析函数应该做你想要的:
select id, row_number() over (partition by id order by id) as col2
from test
order by id;
请参阅此示例SQL Fiddle
给定样本源数据,这将是输出:
| ID | COL2 |
|----|------|
| 10 | 1 |
| 10 | 2 |
| 20 | 1 |
| 20 | 2 |
| 20 | 3 |
| 30 | 1 |
| 30 | 2 |
| 40 | 1 |