I am having some trouble with aggregate functions inside a case
statement. I want to write a query that will set field A to N
if it is equal to the minimum date of field A, or M
otherwise.
Sample Code:
SELECT *, CASE
WHEN Field_A = MIN(FIELD_A) THEN 'JN'
ELSE 'JP'
END AS JUDI
FROM TABLE_1
GROUP BY *
I am not sure why the command runs but does not execute correctly. It labels all rows as JN
in the JUDI
Field. How can I fix this?
I am running SQL Server 7. What I want to achieve is that in a list of rows with different dates it labels those with the earliest date with JN
and subsequent dates with JP
.
Use window functions:
SELECT t.*,
(CASE WHEN t.Field_A = MIN(t.FIELD_A) OVER () THEN 'JN'
ELSE 'JP'
END) AS JUDI
FROM TABLE_1 t;
You don't need aggregation over the entire table for this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.