T-SQL min function with alias for column header

If I do the following in SSMS 2008 r2, using T-SQL:

SELECT TOP 1 [col1] 
FROM [table1] AS ourResult

The alias column header ourResult works as expected.

However, if I do the very similar:

SELECT MIN([Date]) 
FROM [table1] AS min_date1 

the alias for the column header does not work and instead there is:

(No column name)

Is there a fix for this somewhat simple situation?

1 answer

  • answered 2018-01-11 19:41 maSTAShuFu

    This query

    SELECT TOP 1 [col1] 
    FROM [table1] AS ourResult
    

    will return col1 as the columnheader

    but this query

    SELECT MIN([Date]) 
    FROM [table1] AS min_date
    

    will return (No column name) because you wrap the actual column with a function therefore you need a new name or keep the same one by doing this

    SELECT MIN([Date]) as minDate
    FROM [table1] AS min_date
    

    the From clause with "as" is the alias for the table and not the column.