根据同一个表中的不同条件返回列

时间:2017-07-03 04:29:46

标签: sql ms-access

鉴于下表,我希望能够运行一个查询,它将返回两列:一列用于哺乳动物,一列用于其他一切。

id   class
---------
1    reptile
2    bird
3    mammal
4    mammal
5    mammal

预期输出:

mammal  others
--------------
3       1
4       2
5    

我已经尝试了以下(除了其他奇怪的事情),但得到了一个'不能重复表名...来自条款' MS Access中的错误:

SELECT a AS mammals, b AS others
FROM 
(SELECT id AS a FROM animals WHERE class = "mammal"), 
(SELECT id AS b FROM animals WHERE class <> "mammal");

这在SQL中可行吗?谢谢!

2 个答案:

答案 0 :(得分:3)

您需要为查询uniqueclass='mammal'生成class<>'mammal'个数字,然后使用唯一编号加入两个查询。由于class='mammal'class<>'mammal'中的记录数量可能会有所不同,因此我们需要使用FULL OUTER JOIN

但在Ms-Access执行此操作会很痛苦,这不会同时支持Row_NumberFull Outer Join

SELECT * 
FROM   (SELECT a.id, 
               a.class, 
               Count(*) AS Rn 
        FROM   animals a 
               INNER JOIN animals b 
                       ON a.id >= b.id 
        WHERE  b.class = 'mammal' 
        GROUP  BY a.id, 
                  a.class) a 
       LEFT JOIN (SELECT a.id, 
                         a.class, 
                         Count(*) AS Rn 
                  FROM   animals a 
                         INNER JOIN animals b 
                                 ON a.id >= b.id 
                  WHERE  a.class <> 'mammal' 
                  GROUP  BY a.id, 
                            a.class) b 
              ON a.rn = b.rn 
UNION ALL 
SELECT * 
FROM   (SELECT a.id, 
               a.class, 
               Count(*) AS Rn 
        FROM   animals a 
               INNER JOIN animals b 
                       ON a.id >= b.id 
        WHERE  b.class = 'mammal' 
        GROUP  BY a.id, 
                  a.class) a 
       RIGHT JOIN (SELECT a.id, 
                          a.class, 
                          Count(*) AS Rn 
                   FROM   animals a 
                          INNER JOIN animals b 
                                  ON a.id >= b.id 
                   WHERE  a.class <> 'mammal' 
                   GROUP  BY a.id, 
                             a.class) b 
               ON a.rn = b.rn 
WHERE  a.rn IS NULL 

注意:我不太确定Ms-Access语法可能需要一些关于连接的泛神论者,但这应该会给你一个开始的想法

答案 1 :(得分:0)

尝试这可能会有所帮助

select id as Mammal , null as Others from table where class='mammal'
union
select null as Mammal , id as Others from table where class<>'mammal'