tags:

views:

58

answers:

2

I'd like to do an insert select where the select statement has aggregate columns for use by a "HAVING" clause, but where I do not actually want those columns to be inserted. A simple example:

INSERT INTO table1 ( a ) 
SELECT  a, MAX (b) AS maxb FROM table2
GROUP BY a
HAVING maxb = 1

Of course, this won't work because there are a different number of columns in the INSERT and the SELECT. Is there as simple way to make this work? I was hoping I could define some sort of null column in the INSERT field list, or something. I was hoping to avoid a subquery in my SELECT statement, although I could probably do it that way if necessary.

A: 
INSERT INTO table1 ( a ) 
SELECT a FROM (SELECT  a, MAX (b) AS maxb FROM table2
GROUP BY a
HAVING maxb = 1) t
AlbertEin
+1  A: 

You can rewrite the query like this

INSERT INTO table1 ( a ) 
SELECT  a  FROM table2
GROUP BY a
HAVING  MAX (b) = 1
Kibbee