Search code examples
sqlderby

Combine SQL query result with another query statement under one query? (Complicated)


I currently want to combine two SQL queries into one. This is a bit similar to SQL: Taking the result of of query and using it another - combine. Suppose there are two queries:

SQL Statement

1.) SELECT * 
    FROM (SELECT B.example1  
          FROM EXAMPLE1A A  
          INNER JOIN EXAMPLE1B B ON A.ID = B.ID  
          WHERE A.ABC ='ABC' 
          ORDER BY A.ORDER_BY ) as colstate

2.) SELECT colstate 
    FROM EXAMPLE_TABLE 
    WHERE EFG LIKE '%' 
      AND BGTHAN >= '1' 
      AND SMTHAN <= '100' 
    ORDER BY ORDER_BY ASC

I want to use the result in query 1.) as the colstate (column statement) in query 2.). But:

What Have I tried is:

SELECT (SELECT B.example1  
        FROM EXAMPLE1A A  
        INNER JOIN EXAMPLE1B B 
           ON A.ID = B.ID  
        WHERE A.ABC ='ABC' 
        ORDER BY A.ORDER_BY ) 
FROM EXAMPLE_TABLE 
WHERE EFG LIKE '%' 
  AND BGTHAN >= '1' 
  AND SMTHAN <= '100' 
ORDER BY ORDER_BY ASC

And it turns out to be Error: Scalar subquery is only allowed to return a single row, how should I replace the "=" into "IN"? Or is my statement totally wrong?


Solution

  • "Combine two queries into one" - that's not a good specs. Try to find out what exactly you want to get as a FLAT 2-dimensional table, think of nested SELECTs as of nested loops where the inner one can only set a single value for parent's row. Like this:

    [Outer loop - parent row]
        [Inner loop - children rows]
            // all you can do here is change a single parent's field to anything
            // like constant/sum/avg/topmost/ugly-subquery-returning-a-single-result
        [/Inner loop]
    [/Outer loop]