我们如何实现这一目标?
实际表格:
.-------.---------.-------.------.---------.
| EmpId | Project | Title | Role | Values |
|-------|---------|-------|----- |---------|
| 1 | aaa |xxx | A| 100|
| 1 | aaa |yyy | B| 120|
| 1 | aaa |zzz | C| 90|
.-------.---------.-------.------.---------.
目标1:
.-------.---------.-------.----.----.----.
| EmpId | Project | Title | A | B | C |
|-------|---------|-------|--- |----|----|
| 1 | aaa |xxx | 100|null|null|
| 1 | aaa |yyy |null| 120|null|
| 1 | aaa |zzz |null|null| 90|
.-------.---------.-------.----.----.----.
目标2:
.-------.---------.----.----.----.
| EmpId | Project | A | B | C |
|-------|---------|--- |----|----|
| 1 | aaa | 100| 120| 90|
.-------.---------.----.----.----.
条件:
在目标1中,动态生成了A
/ B
/ C
列。(数据透视表,不断更改的列名) 。
A / B / C列实际上不是A / B / C。它是数据透视表或存储过程的结果。可以是A / B / C / D或M / N或X / Y / Z。
列Title
在目标2中根本不重要。
答案 0 :(得分:0)
只需使用聚合:
select EmpId, Project, max(A) as a, max(B) as b, max(C) as c
from t
group by EmpId, Project;
答案 1 :(得分:0)
使用聚合。 MAX()
会忽略NULL
个值:
SELECT empid, project, MAX(A) as A, MAX(B) as B, MAX(C) as C
FROM mytable
GROUP BY empid, project
| empid | project | A | B | C |
| ----- | ------- | --- | --- | --- |
| 1 | aaa | 100 | 120 | 90 |
答案 2 :(得分:0)
SELECT
T1.EmpId,
T1.Project,
T2.A,
T3.B,
T4.C
FROM
Table T1
LEFT JOIN
Table T2 ON
T2.EmpId=T1.EmpId
AND T2.Project=T1.Project
AND T2.A IS NOT NULL
LEFT JOIN
Table T3 ON
T3.EmpId=T1.EmpId
AND T3.Project=T1.Project
AND T3.B IS NOT NULL
LEFT JOIN
Table T4 ON
T4.EmpId=T1.EmpId
AND T4.Project=T1.Project
AND T4.B IS NOT NULL
答案 3 :(得分:0)
with cte (id,pro,title,rol,val) as (
select 1,'aaa','xxx','A',100 union all
select 1,'aaa','yyy','B',120 union all
select 1,'aaa','zzz','C',90)
select id,pro,title,[a],[b],[c] from (
select * from cte ) a
pivot
(max(val) for rol in ([a],[b],[c])) aa
with cte (id,pro,title,rol,val) as (
select 1,'aaa','xxx','A',100 union all
select 1,'aaa','yyy','B',120 union all
select 1,'aaa','zzz','C',90)
select id,pro,max([a]) A,max([b]) B,max([c]) C from (
select * from cte ) a
pivot
(max(val) for rol in ([a],[b],[c])) aa
group by id,pro