您好 我有两个表以下列方式相关:
Table1
gene goterms
ape 1a
ape 1b
ape 1c
boy 2a
boy 1a
cat 1a
cat 1c
Table2
gene gene count
ape ape 3
ape boy 1
ape cat 2
boy ape 1
boy boy 2
boy cat 1
cat ape 2
cat boy 1
cat cat 2
现在,我需要与table2的第二行对应的值 =(计数)/(表1中的猿数+表1中的男孩数) - 计数
[ape boy 1]行,值= 1 /((3 + 2) - 1)= 0.25
类似于table2中的所有其他行。
输出必须类似于
表3 基因基因计数 猿猿3 1 猿男孩1 .25 猿猫2.5 男孩猿1 .25 男孩男孩2 1 男孩猫1 .2 猫猿2 .5 猫男孩1.2 猫猫2 1
我需要一个sql查询,我试图在很多方面,但徒劳无功。
谢谢...
答案 0 :(得分:2)
SELECT基因,gene2,count,count /((SELECT count()FROM Table1 t1 在哪里t2.gene = t1.gene)+(SELECT count()FROM Table1 t1 WHERE t2.gene2 = t1.gene) - count)作为值来自Table2 t2
输出:
gene gene2 count value
ape ape 3 1.0000
ape boy 1 0.2500
ape cat 2 0.6667
boy ape 1 0.2500
boy boy 2 1.0000
boy cat 1 0.3333
cat ape 2 0.6667
cat boy 1 0.3333
cat cat 2 1.0000
答案 1 :(得分:1)
表2中有重复的列名。假设表2的第一列是“基因”而第二列是“gene2”:
Select *
, [Count]
/ ( Coalesce(Gene1.Total,0) + Coalesce(Gene2.Total,0) - Coalesce(Table2.Count,0))
From Table2
Left Join (
Select T1.gene, Count(*) As Total
From Table1 As T1
Group By T1.gene
) As Gene1
On Gene1.gene = Table2.gene
Left Join (
Select T2.gene, Count(*) As Total
From Table1 As T2
Group By T2.gene
) As Gene2
On Gene2.gene = Table2.gene2
Where ( Coalesce(Gene1.Total,0) + Coalesce(Gene2.Total,0) - Coalesce(Table2.Count,0)) > 0
当然,如果您有大量数据,这不会是世界上最快的查询。
使用SQL Server 2008,你可以使用像这样的公用表表达式来编写它更清晰:
With CountByGene As
(
Select T1.gene, Count(*) As Total
From Table1 As T1
Group By T1.gene
)
Select *
, [Count]
/ ( Coalesce(Gene1.Total,0) + Coalesce(Gene2.Total,0) - Coalesce(Table2.Count,0))
From Table2
Left Join CountByGene As Gene1
On Gene1.gene = Table2.gene
Left Join CountByGene As Gene2
On Gene2.gene = Table2.gene2
Where ( Coalesce(Gene1.Total,0) + Coalesce(Gene2.Total,0) - Coalesce(Table2.Count,0)) > 0
答案 2 :(得分:0)
SELECT gene, count(*) AS value FROM Table1 GROUP BY gene;
将为您提供表1中每个基因的计数。
SELECT value FROM ( SELECT gene, count(*) as value FROM Table1 GROUP BY gene; ) WHERE gene = 'boy';
将为您提供子选择语句中的值。
这听起来像是家庭作业所以我只是给出这个答案作为暗示。
答案 3 :(得分:0)
SELECT gene,gene2,count,count /((SELECT count()FROM Table1 t1 WHERE t2.gene = t1.gene)+(SELECT count()FROM Table1 t1 WHERE t2.gene2 = t1.gene) - count)as calc FROM Table2 t2