找到最大总和的日期

时间:2013-11-01 13:07:31

标签: sql date group-by max min

我有一个交易,账户,盈利/亏损和日期的数据库。我需要找到账户中出现最大利润的日期。我已经找到了找到这些实际最大/最小值的方法,但我似乎无法从中提取实际日期。到目前为止我的代码是这样的:

Select accountnum, min(ammount)
from table
where date > '02-Jan-13'
group by accountnum
order by accountnum

理想情况下,我希望看到帐号,最小值或最大值,然后是发生此日期的日期。

3 个答案:

答案 0 :(得分:0)

尝试这样的方法来获取每位客户的最低和最高金额以及发生的日期。

WITH max_amount as (
    SELECT accountnum, max(amount) amount, date
    FROM TABLE
    GROUP BY accountnum, date
),
min_amount as (
    SELECT accountnum, min(amount) amount, date
    FROM TABLE
    GROUP BY accountnum, date
)
SELECT t.accountnum, ma.amount, ma.date, mi.amount, ma.date
FROM table t
JOIN max_amount ma
ON   ma.accountnum = t.accountnum
JOIN min_amount mi
ON   mi.accountnum = t.accountnum

如果您想要今年的数据,可以在语句末尾添加where子句

WHERE t.date > '02-Jan-13'

答案 1 :(得分:0)

最简单的方法是使用窗口/分析函数。这些是ANSI标准,大多数数据库都支持它们(MySQL和Access是两个值得注意的例外)。

这是一种方式:

select t.accountnum, min_amount, max_amount,
       min(case when amount = min_amount then date end) as min_amount_date,
       min(case when amount = min_amount then date end) as max_amount_date,
from (Select t.*,
             min(amount) over (partition by accountnum) as min_amount,
             max(amount) over (partition by accountnum) as max_amount
      from table t
      where date > '02-Jan-13'
     ) t
group by accountnum, min_amount, max_amount;
order by accountnum

子查询使用min()作为窗口函数计算每个帐户的最小和最大金额。外部查询选择这些值。然后,它使用条件聚合来获取每个值发生时的第一个日期。

答案 2 :(得分:0)

;with cte as
(
  select accountnum, ammount, date, 
  row_number() over (partition by accountnum order by ammount desc) rn,
  max(ammount) over (partition by accountnum) maxamount,
  min(ammount) over (partition by accountnum) minamount
  from table
  where date > '20130102'
)
select accountnum, 
       ammount as amount, 
       date as date_of_max_amount, 
       minamount, 
       maxamount 
from cte where rn = 1