MS访问多个查询左连接

时间:2014-06-07 07:26:32

标签: sql ms-access join

我在MS ACCESS中使用多个子查询创建一个表,使得第一个表包含整个集合,剩下的是基于另一个条件 - 这是我的代码

    SELECT a.id, 
           a.cnt AS Total_Count, 
           b.cnt AS Income_Count 
    INTO   data 
    FROM   (SELECT id, 
                   Count(*) AS Cnt 
            FROM   test 
            GROUP  BY id) AS a 
           LEFT JOIN (SELECT id, 
                             Count(*) AS Cnt 
                      FROM   test 
                      WHERE  inc > 25 
                      GROUP  BY id) AS b 
                  ON a.id = b.id; 

It works fine. But when I am putting another sub query its not working 

SELECT a.id, 
       a.cnt AS Total_Count, 
       b, 
       b.cnt AS Income_Count, 
       c.cnt AS EXP_Count 
INTO   data 
FROM   (SELECT id, 
               Count(*) AS Cnt 
        FROM   test 
        GROUP  BY id) AS a 
       LEFT JOIN (SELECT id, 
                         Count(*) AS Cnt 
                  FROM   test 
                  WHERE  inc > 25 
                  GROUP  BY id) AS b 
              ON a.id = b.id 
       LEFT JOIN (SELECT id, 
                         Count(*) AS Cnt 
                  FROM   test 
                  WHERE  exp > 25 
                  GROUP  BY id) AS c 
              ON a.id = c.id; 

你能帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

SELECT a.id, 
       a.cnt AS Total_Count, 
       b,  <----------------- What is this? b is an alias for a table, not a field  
       b.cnt AS Income_Count, 
       c.cnt AS EXP_Count 
INTO   data 
FROM   (SELECT id, 
               Count(*) AS Cnt 
        FROM   test 
        GROUP  BY id) AS a 
       LEFT JOIN (SELECT id, 
                         Count(*) AS Cnt 
                  FROM   test 
                  WHERE  inc > 25 
                  GROUP  BY id) AS b 
              ON a.id = b.id 
       LEFT JOIN (SELECT id, 
                         Count(*) AS Cnt 
                  FROM   test 
                  WHERE  exp > 25 
                  GROUP  BY id) AS c 
              ON a.id = c.id; 

删除&#39; b&#39;或用实际字段替换它。请注意,如果您使用b.id,那么在尝试创建两个具有相同名称的列时会遇到问题&#39; id&#39;你必须改变其中一个的名字。我在sql服务器上运行它,没有&#39; b&#39;。