从一列中选择min(date),max(date)和group by-SQL

时间:2022-09-27 10:27:06

I'm going nuts soon please help.

我很快就疯了,请帮忙。

I have one column containing datetime values.

我有一列包含日期时间值。

I need to find min and max for every day.

我需要每天找到最小值和最大值。

The data looks like this

数据看起来像这样

2012-11-23 05:49:26.000  
2012-11-23 07:55:43.000  
2012-11-23 13:59:56.000  
2012-11-26 07:51:13.000  
2012-11-26 10:23:31.000  
2012-11-26 10:25:09.000  
2012-11-26 16:22:22.000  
2012-11-27 07:30:03.000  
2012-11-27 08:53:47.000  
2012-11-27 10:40:55.000  

This is what tried so far

到目前为止这是尝试过的

select distinct(convert(nvarchar, datum, 112)), min(datum), max(datum) 
from myTable

but when I

但是当我

Group by

I group on all 3 columns...

我对所有3列进行分组......

I seems not to work to set my first select as ColName and Group on this

我似乎没有努力将我的第一个选择设置为ColName和Group

This is what I want

这就是我要的

20121123 | 2012-11-23 05:49:26.000 | 2012-11-23 13:59:56.000  
20121126 | 2012-11-26 07:51:13.000 | 2012-11-26 16:22:22.000  
20121127 | 2012-11-27 07:30:03.000 | 2012-11-27 10:40:55.000  

2 个解决方案

#1


8  

select
  min(datum), max(datum), CONVERT(varchar(8), datum, 112)
from
  dateTable
group by CONVERT(varchar(8), datum, 112)

Here is a fiddle

这是一个小提琴

#2


2  

In SQL Server 2008+, you can use the date data type instead of converting to a character string:

在SQL Server 2008+中,您可以使用日期数据类型而不是转换为字符串:

select cast(datum as date), min(datum), max(datum) 
from myTable
group by cast(datum as date);

#1


8  

select
  min(datum), max(datum), CONVERT(varchar(8), datum, 112)
from
  dateTable
group by CONVERT(varchar(8), datum, 112)

Here is a fiddle

这是一个小提琴

#2


2  

In SQL Server 2008+, you can use the date data type instead of converting to a character string:

在SQL Server 2008+中,您可以使用日期数据类型而不是转换为字符串:

select cast(datum as date), min(datum), max(datum) 
from myTable
group by cast(datum as date);