我有一个交易、账户、损益和日期的数据库。我需要按帐户查找最大利润发生的日期。我已经找到了一种方法来找到这些实际的最大值/最小值,但我似乎无法从中提取实际日期。到目前为止,我的代码是这样的:
Select accountnum, min(ammount)
from table
where date > '02-Jan-13'
group by accountnum
order by accountnum
理想情况下,我希望查看帐户编号、最小值或最大值,然后查看发生日期。
尝试这样的事情来获取每个客户的最小和最大金额以及它发生的日期。
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'
最简单的方法是使用窗口/分析函数。这些是 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()
子查询使用窗口函数计算每个帐户的最小和最大金额。外部查询选择这些值。然后,它使用条件聚合来获取每个值出现的第一个日期。
;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