每年带有标志的最小日期
Minimum date per year with flag
您好,我在客户 table 中有以下数据。
CUST_ID DATE
ab13563590 6/1/2008
ab13563591 1/1/2008
ab13563592 2/1/2008
ab13563593 8/1/2010
ab13563594 7/1/2010
ab13563595 9/1/2008
ab13563596 4/1/2008
ab13563597 10/1/2008
ab13563598 3/1/2009
ab13563599 5/1/2009
我需要一个经过计算的标志,每年的最短日期为 'Y',其余年份的最短日期为 'N'。预期数据应如下所示
CUST_ID DATE FLAG
ab13563590 6/1/2008 N
ab13563591 1/1/2008 Y
ab13563592 2/1/2008 N
ab13563593 8/1/2010 N
ab13563594 7/1/2010 Y
ab13563595 9/1/2008 N
ab13563596 4/1/2008 N
ab13563597 10/1/2008 N
ab13563598 3/1/2009 Y
ab13563599 5/1/2009 N
我所做的是,我使用 min(date) 按年分组并将数据加载到临时 table 并返回到实际 table 并写了一个案例陈述。但我想它可以在一个 select 语句中解决。
提前致谢
您可以使用 Window 函数解决此问题:
SELECT cust_id,
date,
CASE WHEN date = min(date) OVER (PARTITION BY EXTRACT(YEAR FROM date) ORDER BY date) THEN 'Y' ELSE 'N' END AS Flag
FROM table;
这会将当前行的日期与该年的最小日期进行比较。如果它们相等,那么你会得到 'Y'.
试试这个:
select cust_id,date,
case
when date = (select min(date) as min_date from customer where to_char(cust.date,'yyyy') = to_char(date,'yyyy'))
then 'Y' else 'N' end as flag
from customer cust
您好,我在客户 table 中有以下数据。
CUST_ID DATE
ab13563590 6/1/2008
ab13563591 1/1/2008
ab13563592 2/1/2008
ab13563593 8/1/2010
ab13563594 7/1/2010
ab13563595 9/1/2008
ab13563596 4/1/2008
ab13563597 10/1/2008
ab13563598 3/1/2009
ab13563599 5/1/2009
我需要一个经过计算的标志,每年的最短日期为 'Y',其余年份的最短日期为 'N'。预期数据应如下所示
CUST_ID DATE FLAG
ab13563590 6/1/2008 N
ab13563591 1/1/2008 Y
ab13563592 2/1/2008 N
ab13563593 8/1/2010 N
ab13563594 7/1/2010 Y
ab13563595 9/1/2008 N
ab13563596 4/1/2008 N
ab13563597 10/1/2008 N
ab13563598 3/1/2009 Y
ab13563599 5/1/2009 N
我所做的是,我使用 min(date) 按年分组并将数据加载到临时 table 并返回到实际 table 并写了一个案例陈述。但我想它可以在一个 select 语句中解决。
提前致谢
您可以使用 Window 函数解决此问题:
SELECT cust_id,
date,
CASE WHEN date = min(date) OVER (PARTITION BY EXTRACT(YEAR FROM date) ORDER BY date) THEN 'Y' ELSE 'N' END AS Flag
FROM table;
这会将当前行的日期与该年的最小日期进行比较。如果它们相等,那么你会得到 'Y'.
试试这个:
select cust_id,date,
case
when date = (select min(date) as min_date from customer where to_char(cust.date,'yyyy') = to_char(date,'yyyy'))
then 'Y' else 'N' end as flag
from customer cust