简体   繁体   中英

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'.

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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM