Question

I need to using both "union" and "into" in a query. These two versions works ok

SELECT x.* INTO 
 NewTABLE FROM
   (SELECT * FROM TABLE1 UNION SELECT * FROM TABLE2) x

Or

SELECT x.* INTO 
 NewTABLE FROM
   (SELECT val1, val2 FROM TABLE1 UNION SELECT val1, val2 FROM TABLE2) x

But what i need is something like this

SELECT x.* INTO 
 NewTABLE FROM
   (SELECT val1, sum(Iif(val2<0,0,val2)) as PositiveVal2 FROM TABLE1 
    UNION SELECT val1, sum(Iif(val2<0,0,val2)) as PositiveVal2 FROM TABLE2) x

It looks like the sum and/or Iif is the problem. How should I solve this problem!?

Was it helpful?

Solution

You forgot the GROUP BY in your union selects.

SELECT x.* INTO 
 NewTABLE FROM
   (SELECT val1, sum(Iif(val2<0,0,val2)) as PositiveVal2 
    FROM TABLE1 GROUP BY Val1
    UNION 
    SELECT val1, sum(Iif(val2<0,0,val2)) as PositiveVal2 
    FROM TABLE2 GROUP BY Val1) x

You must either aggregate or GROUP BY all select fields in an aggregate query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top