0

Query:

 SELECT business.bussId,
 (select count(invoices.userId) from invoice where invoice.userId = '3000' ) 
 as invoiceCount,    
 (select SUM(invoices.price) from invoice where invoice.userId = '3000' )
 as invoiceprice ,
 FROM business WHERE business.bussId=100

How could I get invoice price and invoiceCount using one nested select ?

1
  • can you put your tables here? Commented Nov 14, 2014 at 12:52

1 Answer 1

2

Move the subquery to the from clause:

SELECT b.bussId, i.invoiceCount, i.invoiceprice
FROM business b cross join
     (select count(i.userId) as invoiceCount, SUM(i.price) as invoiceprice
      from invoice i
      where i.userId = '3000'
     ) i
WHERE b.bussId = 100;

You can actually write this without the subquery, but your question is specifically about using subqueries.

That form would be:

SELECT b.bussId, count(i.userId) as invoiceCount, SUM(i.price) as invoiceprice
FROM business b left join
     invoice i
     on i.userId = '3000' and b.bussId = 100
GROUP BY b.bussId;
Sign up to request clarification or add additional context in comments.

2 Comments

thank new for you answer, no, I don't want to use left join, what does cross join do ?
A cross join creates a cartesian product between the two tables. When one of the tables has just one row (as is presumably true in this case), it just adds the extra columns to the result set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.