0

I want a set of data from Order files that give me CustomerNumber, Order Number, Product, Quantity, Price in addition to number of rows in order detail file for each order. I am having trouble with the last part.

Select Header.CustNo, Header.OrderNumber, Detail.SKU, 
   Detail.Quantity, Detail.Price, Count(Detail2) from Header
   left join Detail on (Header.OrderNumber= Detail.OrderNumber )
   left join Detail as Detail2 on (Header.OrderNumber= Detail2.OrderNumber )
4
  • there is a missing comma here : Detail.Price Count(Detail2) Also I don't get why you do twice the same join. Commented Jan 12, 2012 at 1:59
  • second time I want to do a count on detail lines, but this is clearly not the syntax. I am reading up on subselects but my head she is hurting Commented Jan 12, 2012 at 2:01
  • You're missing a group-by clause. You're got multiple fields that are NOT being aggregated, and mysql will not know how to arrange things to do the count(). Commented Jan 12, 2012 at 2:02
  • I want to group on order number.. in a subselect or WITH clause? Commented Jan 12, 2012 at 2:03

1 Answer 1

2

Is this what you mean? :

SELECT Header.CustNo,
       Header.OrderNumber,
       Detail.SKU, 
       Detail.Quantity,
       Detail.Price,
       ( SELECT COUNT(1)
           FROM Detail AS Detail2
          WHERE Detail2.OrderNumber = Header.OrderNumber
       )
  FROM Header
  LEFT
  JOIN Detail
    ON Header.OrderNumber = Detail.OrderNumber
;
Sign up to request clarification or add additional context in comments.

3 Comments

dont't need a GROUP BY in subselect?
@MustaphaGeorge: No, because you only want it to return a single row. (Notice that it's a correlated subquery: it refers to the Header.OrderNumber from the outer query.)
bonzai! it works!! much simpler than what I was working on with temporary tables..

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.