Er Anup Ray
Er Anup Ray

Reputation: 69

Using Aggregate Function in sql

Why this query is not working:-

SELECT b.byhub, 
       Count(awbno) 
FROM   (SELECT awbno, 
               byhub, 
               entrydatetime, 
               Max(entrydatetime) 
        FROM   wbbooking 
        GROUP  BY awbno, 
                  byhub, 
                  entrydatetime) B 
       INNER JOIN (SELECT refno, 
                          Max(entrydatetime) 
                   FROM   wbmmreceiving 
                   GROUP  BY refno) R 
               ON B.awbno = R.refno 
WHERE  CONVERT(DATE, b.entrydatetime) BETWEEN '2016-10-13' AND '2016-10-13' 
GROUP  BY b.byhub 

After Execute this query I have obtain this type of Error:-

Msg 8155, Level 16, State 2, Line 2
No column name was specified for column 4 of 'b'.
Msg 8155, Level 16, State 2, Line 3
No column name was specified for column 2 of 'r'.

Upvotes: 1

Views: 65

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112762

The errors occur, because you have not specified a name for the aggregate column Max(entrydatetime). Change it to Max(entrydatetime) AS max_entrydatetime.

This query is a bit strange. The subquery B selects entrydatetime as well as Max(entrydatetime). But since entrydatetime is included in the group by list, Max(entrydatetime) will always be the same as entrydattetime.

If you want the last entrydatetime per awbno and byhub, then don't group by entrydatetime and only include it as Max(entrydatetime) in the select list. If you really want to group by this date column, then don't include it as Max(entrydatetime).

What is the purpose of the second subquery? None of its returned columns are used except for joining. Is it needed for the count?

Why include a where-clause in the outer query? If you include it in the first subquery, it is more efficient and the entrydatetime column needs not to be returned any more.

Upvotes: 2

Giorgos Altanis
Giorgos Altanis

Reputation: 2760

Just specify column names for your subqueries, like this:

SELECT b.byhub, 
       Count(awbno) 
FROM   (SELECT awbno, 
               byhub, 
               entrydatetime, 
               Max(entrydatetime) max_entrydatetime
        FROM   wbbooking 
        GROUP  BY awbno, 
                  byhub, 
                  entrydatetime) B 
       INNER JOIN (SELECT refno, 
                          Max(entrydatetime) max_entrydatetime
                   FROM   wbmmreceiving 
                   GROUP  BY refno) R 
               ON B.awbno = R.refno 
WHERE  CONVERT(DATE, b.entrydatetime) BETWEEN '2016-10-13' AND '2016-10-13' 
GROUP  BY b.byhub 

Upvotes: 1

Related Questions