Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select min(date), max(date) and group by day from one column - SQL

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

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

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  
like image 691
m0rte0 Avatar asked Oct 08 '14 20:10

m0rte0


People also ask

How can I get data from a specific day in SQL?

If you want to get a day from a date in a table, use the SQL Server DAY() function. This function takes only one argument – the date. This can be a date or date and time data type. (In our example, the column VisitDate is of the date data type.)

How do I select both min and max in SQL?

To ask SQL Server about the minimum and maximum values in a column, we use the following syntax: SELECT MIN(column_name) FROM table_name; SELECT MAX(column_name) FROM table_name; When we use this syntax, SQL Server returns a single value. Thus, we can consider the MIN() and MAX() functions Scalar-Valued Functions.

Can we use max with GROUP BY in SQL?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

Can we use max and min together in SQL?

You can use both the MIN and MAX functions in one SELECT . If you use only these functions without any columns, you don't need a GROUP BY clause.


2 Answers

Convert the column in the GROUP BY as well.

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

Here is a fiddle

Here are the list of convert values for dates. (I've chosen 112 for you in this case above)

like image 172
crthompson Avatar answered Sep 25 '22 11:09

crthompson


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

select cast(datum as date), min(datum), max(datum) 
from myTable
group by cast(datum as date);
like image 34
Gordon Linoff Avatar answered Sep 21 '22 11:09

Gordon Linoff