我有一张有这种记录的表
ID wk category mo tu wedn
1 1 3 4 4 4
1 1 4 5 5 5
1 1 18 7 7 7
1 2 3 4 4 4
1 2 4 5 5 5
1 2 17 2 2 2
如何连接行具有相同的类别,并保持wk = 1和wk = 2的不匹配行以及类似以下内容 来自wk = 2的数据需要来自wk = 1的数据:
ID category mo tu wedn mo2 tu2 wedn2
1 3 4 4 4 4 4 4
1 4 5 5 5 5 5 5
1 18 7 7 7 0 0 0
1 17 0 0 0 2 2 2
谢谢,
答案 0 :(得分:2)
运行完整的外部联接,并使用select
NVL(a.id, b.id)
, NVL(a.category, b.category)
, NVL(a.mo, 0)
, NVL(a.tu, 0)
, NVL(a.wedn, 0)
, NVL(b.mo, 0) as mo2
, NVL(b.tu, 0) as tu2
, NVL(b.wedn, 0) as wedn2
from MyTable a
full outer join MyTable b ON a.id=b.id AND a.wk=1 AND b.wk=2 AND a.category=b.category
where (a.wk is null or a.wk <> 2) and (b.wk is null OR b.wk <> 1)
来区分哪些行转到哪一侧 - 左侧或右侧:
data.table