MSSQL中的简单查询。选择

时间:2017-03-24 13:49:25

标签: sql-server select

我是MSSQL的基本用户。我无法正确完成查询。这应该是一个简单的问题。

这是我的代码:

SELECT Pass_in_trip.date, Count(date) as numbOfPassengers
From Pass_in_trip, Trip
WHERE (Trip.trip_no = Pass_in_trip.trip_no AND Trip.town_from='Rostov')
Group BY date
HAVING COUNT(date) = 3

这种方式确实有效。但我想比较COUNT(日期)和MAX(COUNT(日期))然后我遇到问题:

  

无法对包含的表达式执行聚合函数   聚合或子查询。

1 个答案:

答案 0 :(得分:1)

我认为这可能就是你要找的东西。

公用表表达式有助于避免重复查询。

WITH cte as
  (
    SELECT Pass_in_trip.date, Count(date) as numbOfPassengers
    FROM Pass_in_trip
    INNER JOIN Trip 
       ON Trip.trip_no = Pass_in_trip.trip_no
    WHERE Trip.town_from='Rostov'
    GROUP BY date
  )
SELECT date, numbOfPassengers
FROM cte
WHERE numbOfPassengers = (SELECT MAX(numbOfPassengers) FROM cte)