简体   繁体   中英

MS access multiple query left join

I am creating a table in MS ACCESS using multiple sub query in a way such that 1st table contains the whole set and remaining are based on some another condition - here is my code

    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; 

Can you please help me on this.

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; 

Remove the 'b' or replace it with an actual field. Be careful, if you use b.id then you will run into issues with trying to create two columns with the same name 'id' you will have to change the name of one of them. I ran this on a sql server an it worked fine without the 'b'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM