T-SQL stored procedure - "Cannot perform an aggregate function on an expression containing an aggregate or a subquery."


I am writing a query to return an resultset as follows:
select       Weldment = p.partName,
      NbrProduced = sum(p.qtyExpected),
      Batches = sum(1),
      AvgWeldTime = AVG(DATEDIFF(hh,
                            (SELECT TOP 1 transactiontime trans
                              FROM vtransaction t2
                              WHERE t2.partid = t.partid AND t2.transactiontype = 9 and t2.parkinglotid=@lotid
                              ORDER BY transactionTime DESC),
from vtransaction t
left join vparts p on t.partId = p.id
where t.parkinglotid in (select downstreamid from vparkinglotdependencies where parkinglotid = @lotid)
      and t.transactiontime < @dateto
      and t.transactiontime > @datefrom
      and t.transactionType = 8
      and p.partname is not null
      and p.parttype = 'weldment'
group by p.partName

I want to calculate the number of parts produced and the average time between two types of transactions (transactionType 8 and 9) for each part number (p.partName). Well it doesn't like AvgWeldTime = .... and gives me the error "Cannot perform an aggregate function on an expression containing an aggregate or a subquery."

How can I accomplish this with a single statement?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.


SELECT stuff
FROM  table
WHERE stuff = conditions
GROUP BY stuff
HAVING aggregated_stuff = conditions
Sorry, I misunderstood your question...try the following:
SELECT      Weldment      = p.partName
      ,NbrProduced      = SUM(p.qtyExpected)
      ,Batches      = COUNT(*)
      ,AvgWeldTime      = AVG(DATEDIFF(hh,t2.transactiontime,t.transactiontime))
FROM      vtransaction            t
      INNER JOIN      vparts      p
            ON      t.partId      = p.id
      ,(      SELECT      transactiontime      = MAX(transactiontime)
            FROM      vtransaction      t2
            WHERE      transactiontype      = 9
            AND      parkinglotid      = lotid
            GROUP BY partid
                  ,parkinglotid)      t2
WHERE      t.parkinglotid      IN (      SELECT      downstreamid
                        FROM      vparkinglotdependencies
                        WHERE      parkinglotid      = @lotid)
AND      t.transactiontime      < @dateto
AND      t.transactiontime      > @datefrom
AND      t.transactionType      = 8
AND      p.partname      IS NOT NULL
AND      p.parttype      = 'weldment'
AND      t.partid      = t2.partid
GROUP BY p.partName

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Bryan_WebbAuthor Commented:

Thanks for your reply. Everything worked great after I changed some things around to suit my app (I didn't really want to do an AVG, as it turns out):
,AvgWeldTime = SUM(CONVERT(FLOAT, DATEDIFF(hh,t2.transactiontime,t.transactiontime)))/SUM(p.qtyExpected)

If you don't mind, could you explain what is happening inside the INNER JOIN statement? I don't understand the SELECT and how it affects the INNER JOIN.

Thanks and regards,
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Hi Bryan,

You don't necessarily need to write the words INNER JOIN.  Some people say that the INNER JOIN helps SQL Server figure out what to do faster, but I see little difference to doing the following:

SELECT     Weldment     = p.partName
     ,NbrProduced     = SUM(p.qtyExpected)
     ,Batches     = COUNT(*)
     ,AvgWeldTime     = SUM(CONVERT(FLOAT,DATEDIFF(hh,t2.transactiontime,t.transactiontime)))/SUM(p.qtyExpected)
FROM     vtransaction          t
     ,vparts     p
     ,(     SELECT     transactiontime     = MAX(transactiontime)
          FROM     vtransaction     t2
          WHERE     transactiontype     = 9
          AND     parkinglotid     = @lotid
          GROUP BY partid)     t2
WHERE     t.partId     = p.id
AND     t.parkinglotid     IN (     SELECT     downstreamid
                    FROM     vparkinglotdependencies
                    WHERE     parkinglotid     = @lotid)
AND     t.transactiontime     < @dateto
AND     t.transactiontime     > @datefrom
AND     t.transactionType     = 8
AND     p.partname     IS NOT NULL
AND     p.parttype     = 'weldment'
AND     t.partid     = t2.partid
GROUP BY p.partName

When you have the (SELECT...) in the FROM area, you really are using that query as a table.  I suppose you could do an INNER JOIN with that (SELECT...), but I chose not to.  The INNER JOIN and the ',Table WHERE' is mostly a preference thing in my eyes.

I'm not sure if I answered your question...so I'll stop my babble now.

Hope this helps!
Bryan_WebbAuthor Commented:

I see now, thanks for the explanation.

Cool...not a problem!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.