0

我正在编写一份 SQL Server 2008 报告,该报告将比较动物的基因测试结果。基因测试由动物 ID、基因和结果组成。并非所有动物都会测试相同的基因,但我需要能够并排显示一组给定动物的结果,并且只包括至少一个选定动物存在的基因。

我的 TestResult 表中包含以下数据:

animalId    gene    result
1           a       CC
1           b       CT
1           d       TT
2           a       CT
2           b       CT
2           c       TT
3           a       CT
3           b       TT
3           c       CC
3           d       CC
3           e       TT

我需要生成一个如下所示的结果集。请注意,动物 3 没有显示(用户不想看到它的结果),基因“e”的结果也没有显示,因为动物 1 和动物 2 都没有该基因的结果:

SireID  SireResult  CalfID  CalfResult Gene
1       CC          2       CT          a
1       CT          2       CT          b
1       NULL        2       TT          c
1       TT          2       NULL        d

但我只能设法得到这个:

SireID  SireResult  CalfID  CalfResult Gene
1       CC          2       CT          a
1       CT          2       CT          b
NULL    NULL        2       TT          c
1       TT          NULL    NULL        d

这是我正在使用的查询。

SELECT
    sire.animalId AS 'SireID'
    ,sire.result AS 'SireResult'
    ,calf.animalId AS 'CalfID'
    ,calf.result AS 'CalfResult'
    ,sire.gene AS 'Gene'
FROM
    (SELECT 
        s.animalId 
        ,s.result 
        ,m1.gene 
    FROM
        (SELECT [animalId ]
            ,result 
            ,gene 
        FROM TestResult
        WHERE animalId IN (1)) s
    FULL JOIN
        (SELECT DISTINCT 
            gene 
        FROM TestResult
        WHERE animalId IN (1, 2)) m1
    ON s.marker = m1.marker) sire
FULL JOIN
    (SELECT 
        c.animalId 
        ,c.result 
        ,m2.gene 
    FROM
        (SELECT animalId 
            ,result 
            ,gene 
        FROM TestResult
        WHERE animalId IN (2)) c
    FULL JOIN
        (SELECT DISTINCT 
            gene 
        FROM TestResult
        WHERE animalId IN (1, 2)) m2
    ON c.gene = m2.gene) calf
ON 
    sire.gene = calf.gene

当 SireID 和 CalfID 没有与特定基因关联的记录时,如何让它们显示它们的值?我正在考虑使用 COALESCE,但我不知道如何指定正确的 animalId 传递。任何帮助将不胜感激。

4

1 回答 1

0

我来到了这个:

SELECT A.animalId  AS SireID, A.result AS SireResult, B.animalid  AS CalfID, B.Result AS CalfResult, A.gene
  FROM TestResult A  INNER JOIN  TestResult B
ON A.gene = B.gene 
 WHERE A.animalId = 1 AND B.animalId = 2
 UNION 
SELECT 1 AS SireID, NULL AS SireResult, animalid  AS CalfID, Result AS CalfResult, gene
  FROM TestResult 
 WHERE animalId = 2 and gene not in (select distinct gene from TestResult where animalId = 1)
 UNION 
SELECT animalid AS SireID, Result AS SireResult, 2 AS CalfID, NULL AS CalfResult, gene
  FROM TestResult 
 WHERE animalId = 1 and gene not in (select distinct gene from TestResult where animalId = 2)  
ORDER BY SireID, A.gene, SireResult
于 2012-06-16T03:11:07.637 回答