使用T-SQL分组最小和最大日期

时间:2017-03-04 11:04:11

标签: sql sql-server tsql sql-server-2012

我正在尝试对SF Bay Area Bike Share Kaggel数据

中的数据执行一些SQL

当我运行此SQL时:

/****** Select Bikes   ******/
SELECT count(t.[id]) as TripCount
,t.[bike_id]
FROM [dbo].[trip] t
Group By t.[bike_id]
having count(t.[id]) < 25
Order By TripCount asc

我得到了这个结果:

+-----------+---------+
| TripCount | bike_id |
+-----------+---------+
|         6 |     876 |
|        18 |     323 |
|        20 |     565 |
|        24 |     476 |
|        24 |     697 |
+-----------+---------+

我真正想要的是:

+-----------+---------+------------+------------+
| TripCount | bike_id |  Min_date  |  Max_date  |
+-----------+---------+------------+------------+
|         6 |     876 | 2014-05-22 | 2014-05-27 |
|        18 |     323 | 2013-08-30 | 2013-09-07 |
|        20 |     565 | 2013-08-29 | 2013-09-07 |
|        24 |     476 | 2013-08-29 | 2013-09-07 |
|        24 |     697 | 2013-10-15 | 2013-12-20 |
+-----------+---------+------------+------------+

最小日期&amp;最大日期分别给出第一个&amp;自行车去旅行的最后日期。

我可以通过运行以下方法为每辆自行车手动执行此操作:

SELECT 
min(cast([start_date] as date)) as Min_Date
,max(cast([start_date] as date)) as Max_Date
,[bike_id]
FROM [dbo].[trip]
where bike_id = '697'
Group By bike_id

我尝试了这个查询:

/****** Script for SelectTopNRows command from SSMS  ******/
SELECT 
count (t.[id]) as TripCount
,min(cast(t.[start_date] as date)) as Min_Date
,max(cast(t.[start_date] as date)) as Max_Date
,[bike_id]
FROM [dbo].[trip] t
Group By count (t.[id]), bike_id

并且显然出现以下错误: 不能在GROUP BY子句列表的组表达式中使用聚合或子查询。

只是不太确定如何绕过这个......

1 个答案:

答案 0 :(得分:1)

你很亲密

SELECT
[bike_id] 
,count (t.[id]) as TripCount
,min(cast(t.[start_date] as date)) as Min_Date
,max(cast(t.[start_date] as date)) as Max_Date
FROM [dbo].[trip] t
Group By  bike_id