Insert into x (...)
select a,b,c from prq where p_a is null group by a,b,c
Now, my requirement is that, if p_a is null then i have to group by a,b,c and select only a,b,c column.
But if p_a is not null then, i have to group by two new column x,y and also select these two columns.
These x,y columns are NULLABLE in table x.
Table X must have at least five columns whose names, we can presume, are
a,b,c,x,y.If you are doing a single INSERT, then you’ll need to insert into all five columns. If you are doing multiple INSERT operations, you can insert into 3 and then 5 (or vice versa) columns. You may have to do some juggling with the NULL values in the select-list of the first alternative. I’m assuming that the columns
xandyare INTEGER for definiteness – choose the appropriate type.1st Alternative
You could replace the
GROUP BY a, b, cclause with a DISTINCT in front ofain the select-list of the first part of the UNION. In most SQL DBMS, you must list all the non-aggregate columns from the select-list in the GROUP BY clause. Using the MAX means that you have aggregates forxandyin the first half of the UNION and fora,bandcin the second half of the UNION.2nd Alternative
As discussed before, you need aggregates on the columns not in the GROUP BY list.
3rd Alternative
If you meant that you must group by
xandyas well asa,bandc, then the second half of the UNION (or the second SELECT) simplifies to:Or you can use DISTINCT again: