The fields in the SELECT don't exist before a WHERE. Take a peak at https://blog.sqlauthority.com/2009/04/06/sql-server-logical-query-processing-phases-order-of-statement-execution/.
SQL's normal processing order is:
- FROM
- ON
- OUTER
- WHERE
- GROUP BY
- CUBE | ROLLUP
- HAVING
- SELECT
- DISTINCT
10 ORDER BY
- TOP
So in your query, there is no [maxDate] available yet. To have one available for a WHERE, use a CTE to generate one. Then apply the WHERE.
NOTE: I used INTs for the VALUE()
columns for simplicity's sake.
SQL Fiddle
MS SQL Server 2014 Schema Setup:
CREATE TABLE t (field1 varchar(10), f2 int, f3 int, f4 int ) ;
INSERT INTO t (field1, f2, f3, f4)
VALUES ('first',10,5,0), ('second',1,7,3), ('third',2,4,6) ;
Query 1:
; WITH a AS (
SELECT field1,
(
SELECT Max(v)
FROM (VALUES (f2), (f3), (f4)) AS value(v)
) AS maxF
FROM t
)
SELECT a.field1, a.maxF
FROM a
WHERE a.maxF = 6 ;
Results:
| field1 | maxF |
|--------|------|
| third | 6 |