2

我需要在查询中同时使用“union”和“into”。这两个版本都可以

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

或者

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

但我需要的是这样的

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

看起来总和和/或 Iif 是问题所在。我该怎么解决这个问题!?

4

1 回答 1

1

您在联合选择中忘记了 GROUP BY。

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

您必须聚合或 GROUP BY 聚合查询中的所有选择字段。

于 2012-08-30T11:41:08.327 回答