Skip to content
Advertisement

How to select Maximum and minimum date values and pass those as a query

I have a table with the following entries

CustomeID TransDate WorkID
1 2012-12-01 12
1 2012-12-03 45
1 2013-01-21 3
2 2012-12-23 11
3 2013-01-04 13
3 2013-12-24 16
4 2014-01-02 2

I am trying get the data between two dates and the required date values are minimum and maximum values of the column. I am able to get the desired output when I hard code the values.

SELECT *
FROM dbo.MyTable
WHERE TransDate >= '2012-12-01' AND TransDate <= '2014-01-02'

I am aware the if I remove the where clause it will solve all the issues, But my actual query is much complex and has other conditions. The only way is to get maximum date values and minimum date value from the table and pass that reference to it.

I tried the below step but that does not work and throws the below error.

SELECT *
FROM dbo.MyTable
WHERE TransDate >= '2012-12-01' AND TransDate <= MAX(TransDate) 
    

Error

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

Expected Output:

CustomeID TransDate WorkID
1 2012-12-01 12
1 2012-12-03 45
1 2013-01-21 3
2 2012-12-23 11
3 2013-01-04 13
3 2013-12-24 16
4 2014-01-02 2

Advertisement

Answer

Use a scalar subquery to find the maximum date across the whole table:

SELECT *
FROM dbo.MyTable
WHERE TransDate >= '2012-12-01' AND
      TransDate < (SELECT DATEADD(DAY, 1, MAX(TransDate)) FROM dbo.MyTable);

Note that I am using a strict inequality (less than) in the WHERE clause against one day later than the max date. This will include all days which fall on or earlier than the maximum date.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement