我有下表:
MedicineID Type PlantId category
1223456 ABC P1 A
7821632 DEF P2 B
5436710 GHI P1 D
6743210 ABC P3 A
4321793 THE P4 D
7285743 ABC P1 B
4143521 DEF P3 A
5234345 GHI P2 D
5132451 FGE P1 B
1235432 REF P4 A
5652315 GHI P3 D
6733115 ABC P2 B
7752242 DEF P3 A
2652225 GHI P2 D
6242352 ABC P1 B
Run Code Online (Sandbox Code Playgroud)
我有7种不同类型的药物= [ABC DEF GHI THE FGE REF XYZ]每种药物可以分为4个不同的类别.这些药物是由4种不同的植物制成的.所有植物都有能力制造所有药物.我想知道看一下表中每种类型和每个类别中每种植物制造的药物有多少.我的结果表应该是这样的.
Plant Type A B D
P1 ABC 1 2 0
P1 DEF 0 0 0
P1 GHI 0 0 1
P1 THE 0 0 0
P1 FGE 0 1 0
P1 REF 0 0 0
P1 XYZ 0 0 0
P2 ABC 0 1 0
P2 DEF 0 1 0
P2 GHI 0 0 2
P2 THE 0 0 0
P2 FGE 0 0 0
P2 REF 0 0 0
P2 XYZ 0 0 0
P3 ABC 1 0 0
P3 DEF 2 0 0
P3 GHI 0 0 1
P3 THE 0 0 0
P3 FGE 0 0 0
P3 REF 0 0 0
P3 XYZ 0 0 0
P4 ABC 0 0 0
P4 DEF 0 0 0
P4 GHI 0 0 0
P4 THE 0 0 1
P4 FGE 0 0 0
P4 REF 1 0 0
P4 XYZ 0 0 0
Run Code Online (Sandbox Code Playgroud)
我不确定甚至可以使用哪些命令来开始.任何正确方向的帮助将不胜感激.
如果类别的数量是固定的,您可以简单地使用条件聚合.
select tplant.plantid,ttype.type,
count(case when t.category='A' then t.plant end) A,
count(case when t.category='B' then t.plant end) B,
count(case when t.category='D' then t.plant end) D
from (select distinct type from typetable) ttype --replace typetable with the table that has all the types
cross join (select distinct plantid from tablename) tplant
left join tablename t on t.plantid=tplant.plantid and t.type=ttype.type
group by tplant.plantid,ttype.type
Run Code Online (Sandbox Code Playgroud)