我有一张如下表:
ID TYPE VALUE
1 CC 1 X
1 CC 2 Y
1 CC 3 NULL
1 CC 4 NULL
我使用sql PIVOT和STUFF功能来获得所需的结果,但仍然无法做到。请有人帮我。
期望的结果:
ID [CC 1] [CC 2] [CC 3] [CC 4]
1 X Y NULL NULL
答案 0 :(得分:3)
您可以通过多种方式解决此问题。我通常使用条件聚合:
ModelData *model = [ModelData MR_createEntity];
model.key = modelDataKey;
model.value = value;
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL contextDidSave, NSError *error) {
NSUInteger count = [ModelData MR_countOfEntities];
if (count > 100) {
//remove last element added
}
}];
答案 1 :(得分:0)
FULL OUTER JOIN
的:
select coalesce(t1.id, t2.id, t3.id, t4.id),
t1.value as cc1,
t2.value as cc2,
t3.value as cc3,
t4.value as cc4
from (select id, value from tablename where type = 'CC 1') as t1
full outer join (select id, value from tablename
where type = 'CC 2') as t2 ON t1.id = t2.id
full outer join (select id, value from tablename
where type = 'CC 3') as t3 ON t2.id = t3.id
full outer join (select id, value from tablename
where type = 'CC 4') as t ON t3.id = t4.id
答案 2 :(得分:0)
尝试以下方法:
Select id, listagg(value, '-') within group(order by type) over (partition by id) as txt
From table group by Id, txt
答案 3 :(得分:0)
以下是pivot的语法;
SELECT ID, [CC 1],[CC 2],[CC 3],[CC 4]
FROM yourtable
PIVOT
(min([value])
FOR Type
in([CC 1],[CC 2],[CC 3],[CC 4])
)AS p