简体   繁体   English

Case语句中的聚合函数

[英]Aggregate function inside Case Statement

I am having some trouble with aggregate functions inside a case statement. 我在case语句中的集合函数遇到了一些麻烦。 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. 我想编写一个查询,如果它等于字段A的最小日期,则将字段A设置为N ,否则将字段M设置为N

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. 它将所有行标记为JUDI字段中的JN 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 . 我正在运行SQL Server7。我想要实现的是,在具有不同日期的行列表中,它用JN标记最早的日期,而用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. 您不需要为此在整个表上进行聚合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM