2010-10-28 40 views
1

這裏我們比較基因表記錄:首先將基因a與所有基因a,b,c進行比較,例如aa,ab,ac同樣需要b然後ba,bb ,bc等.......SQL查詢比較單個表中的行

所以這裏匹配的結果是nd b是2,因爲匹配記錄是589,822 bc count的常用基因條件是1,因爲匹配記錄586和它應該是所有其他組合零。

goterm gene auto 
-------------------- 
589  a 1 
822  a 2 
478  a 3 
586  b 4 
589  b 5 
600  c 6 
586  c 7 
822  b 8 

查詢:

select count(*), 
     x.gene, 
     x.ng 
from (select t.gene, 
       v.gene as ng 
     from (select distinct gene 
       from gene) as t 
    cross join (select distinct gene from gene) as v) as x 
    left join (select (g.gene),(n.gene) as ng from gene g 
     join gene n on n.goterm=g.goterm where g.auto<n.auto) as y on y.gene = x.ng 
                    and y.ng = x.gene 
group by x.gene,x.ng 

最後上面查詢的輸出是:

count gene gene 
1  a  a 
2  b  a 
1  c  a 
1  a  b 
1  b  b 
1  c  b 
1  a  c 
1  b  c 
1  c  c 

但輸出必須:

count gene gene 
0  a  a 
2  b  a 
0  c  a 
0  a  b 
0  b  b 
1  c  b 
0  a  c 
0  b  c 
0  c  c 
+0

您應該考慮爲「基因」字段的唯一值設置另一個表格,特別是如果您想要表示的基因有屬性。這將使生產組合更簡單。 – Simon 2010-10-28 16:21:08

+0

@OMG Ponies,@Joe Stefanelli:如果可以,我會幫你格式化這個問題:) hehe – Andomar 2010-10-28 16:27:23

回答

0
select combo1.gene, combo2.gene, count (gene2.goterm) 
from (select distinct gene from gene) combo1 
cross join (select distinct gene from gene) combo2 
join gene gene1 on combo1.gene = gene1.gene 
left join gene gene2 on combo2.gene = gene2.gene 
    and gene1.goterm = gene2.goterm and gene1.auto < gene2.auto 
group by combo1.gene, combo2.gene 
order by combo1.gene, combo2.gene 

編輯:意識到畢竟我並不需要DISTINCT。

+0

非常感謝你....這工作 – user489981 2010-10-29 06:27:52

0

不知道究竟怎麼了你邏輯起作用(特別是c在auto ompare),但這個查詢產生你正在尋找的結果是:

declare @t table (goterm int, gene char(1), auto int identity) 
insert @t 
      select 589,  'a' 
union select all 822,  'a' 
union select all 478,  'a' 
union select all 586,  'b' 
union select all 589,  'b' 
union select all 600,  'c' 
union select all 586,  'c' 
union select all 822,  'b' 

select t1.gene 
,  t2.gene 
,  (
     select COUNT(*) 
     from @t t3 
     join @t t4 
     on  t3.goterm = t4.goterm 
       and t3.auto > t4.auto 
     where t3.gene = t1.gene 
       and t4.gene = t2.gene 
     ) as Total 
from (
     select distinct gene 
     from @t 
     ) t1 
cross join 
     (
     select distinct gene 
     from @t 
     ) t2 
order by 
     t2.gene 
,  t1.gene 

此打印:

gene gene Total 
a  a  0 
b  a  2 
c  a  0 
a  b  0 
b  b  0 
c  b  1 
a  c  0 
b  c  0 
c  c  0 

t1t2在那裏創建基因組合的矩陣。 Total查詢查找該組合的點擊次數。 t3.auto > t4.auto的情況讓我困惑,所以你可能要仔細檢查一下。

+0

在連接中加入'auto'可以防止586 b,c對被計算爲c,b 。 – Simon 2010-10-28 16:43:21

+0

@Simon:你的意思就像問題中所期望的答案一樣? – Andomar 2010-10-28 16:45:05

+0

哦,我讓他們倒退了。但是,它的重點是防止這一對被計算兩次。 – Simon 2010-10-28 17:04:10

0

嘗試在您的查詢中更改count(*)count(y.gene)