Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using group by clause in subquery in sql

Tags:

sql

I am trying to use group by clause in subquery which is in from clause

select userID,count(id) 
from 
(
    (
        select id,max(bidAmount),userID 
        from Bids 
        group by id,bidAmount
    ) 
    group by userID
);

but this gives error

Error: near "group": syntax error

Is it possible to use group by clause in subquery in from clause in sql?

like image 465
vaichidrewar Avatar asked Nov 30 '11 01:11

vaichidrewar


People also ask

Can GROUP BY be used in subquery?

The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery. Subqueries that return more than one row can only be used with multiple value operators such as the IN operator.

Which clause Cannot be used in subquery?

Subqueries cannot manipulate their results internally, that is, a subquery cannot include the order by clause, the compute clause, or the into keyword. Correlated (repeating) subqueries are not allowed in the select clause of an updatable cursor defined by declare cursor.

Can we use GROUP BY in with clause?

GROUP BY clause is used with the SELECT statement. In the query, GROUP BY clause is placed after the WHERE clause. In the query, GROUP BY clause is placed before ORDER BY clause if used any. In the query , Group BY clause is placed before Having clause .

Can HAVING and GROUP BY clauses be used in multiple row subqueries?

Multiple Row Sub Query Multiple-row subqueries are nested queries that can return more than one row of results to the parent query. Multiple-row subqueries are used most commonly in WHERE and HAVING clauses. Since it returns multiple rows, it must be handled by set comparison operators (IN, ALL, ANY).


2 Answers

Check your (), they are not at right places. Should be something more like this:

select w.userID,count(w.id) 
from (select id,max(bidAmount),userID from Bids group by id, userID) w 
group by w.userID
like image 98
勿绮语 Avatar answered Oct 04 '22 18:10

勿绮语


Try this:

select userID,count(id) 
from (

select id,max(bidAmount),userID from Bids group by id,userID

) as tmp

 group by userID
like image 30
Jake Feasel Avatar answered Oct 04 '22 17:10

Jake Feasel