简体   繁体   中英

How to use output of 1st query as input for 2nd one?

I was trying to do this to avoid manual work. not sure if it is possible or not.

First query:

SELECT Max(version), Project 
FROM Table_1 
GROUP_BY project

Second query:

SELECT B.project, B.version, B.defect, B.Assign, C.staus 
FROM Table_2 B 
JOIN Table_3 C ON B.project = C.project AND B.version = C.version
WHERE (B.project = 1 AND B.version = 2)

I want all the latest projects version in that database automatically picked up from the first query and entered in 2nd query.

Thank you for your time.

Join them:

SELECT B.project, B.version, B.defect, B.Assign, C.staus 
FROM Table_2 B JOIN Table_3 C ON B.project = C.project 
                             AND B.version = C.version
join (select max(version) max_version,
             project
      from table_1
      group by project
     ) x on x.project = b.project 
        and x.max_version = b.version;

Using a cte can make things easy to read:

WITH quarry1 AS
(
  SELECT Max(version) as version, Project FROM Table_1 
  GROUP_BY project
)
SELECT B.project, B.version, B.defect, B.Assign, C.staus 
FROM 
    Table_2 B 
    INNER JOIN Table_3 C ON B.project = C.project AND B.version = C.version
    INNER JOIN quarry1 D ON B.project = D.project AND B.version = D.version
WHERE 
    (B.project = 1 and B.version = 2) -- you should probably remove this

  --if you leave the WHERE clause in there is probably no point running the 
  --query that calculates the MAX. I left it in to demo how to put two
  --queries together - i.e. I answered literally the question you asked
  --rather than guessing at what you meant to ask. Think on and fix this

You need to give the MAX an alias - I just used version again. You should endeavour to give tables and aliases good meaningful names though; table1/2/3 a/b/c/d isn't very descriptive and will make the query harder to read, write and debug

In Oracle, you can use in :

SELECT B.project, B.version, B.defect, B.Assign, C.staus 
FROM Table_2 B JOIN
     Table_3 C
     ON B.project = C.project AND B.version = C.version
WHERE (B.project, B.version) IN (SELECT Max(version), Project 
                                 FROM Table_1 
                                 GROUP BY project
                                );

Or a correlated subquery:

SELECT B.project, B.version, B.defect, B.Assign, C.staus 
FROM Table_2 B JOIN
     Table_3 C
     ON B.project = C.project AND B.version = C.version
WHERE B.version = (SELECT MAX(t1.version) 
                   FROM Table_1 t1
                   WHERE t1.project = B.project
                  );

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