我有一张这样的桌子:
------------------------------
|SampleID |DrugName |Result |
------------------------------
|Sample1 |Drug1 |Positive|
|Sample1 |Drug2 |Positive|
|Sample2 |Drug1 |Positive|
|Sample2 |Drug2 |Negative|
|Sample2 |Drug3 |Positive|
......
我想得到
-----------------------
|1stDrug|2ndDrug|Count|
-----------------------
|Drug1 |Drug2 |1 |
|Drug1 |Drug3 |1 |
|Drug2 |Drug3 |0 |
......
我基本上想使用SQL对药物组合呈阳性的样品进行计数。这会让我知道“ Drug1和Drug2在X个样本中均为阳性”,“ Drug 1和Drug 3在Y样本中均为阳性”,等等。由于没有有限的样本ID和大量药物,所以我无法将任何样品ID或药品名称硬编码到查询中。但是,所有列都不为空。
谢谢。
答案 0 :(得分:1)
我想你想要
select t1.drug as drug1, t2.drug as drug2,
sum(case when t1.result = 'positive' and
t2.result = 'positive'
then 1
else 0
end) / 2
from t t1 join
t t2
on t1.sample = t2.sample and t1.drug < t2.drug
group by t1.drug, t2.drug;