简体   繁体   English

查找金额最大的日期

[英]Finding a date with the largest sum

I have a database of transactions, accounts, profit/loss, and date. 我有一个交易,账户,损益和日期数据库。 I need to find the dates which the largest profit occurs by account. 我需要找到最大利润发生日期的帐户。 I have already found a way to find these actually max/min values but I can't seem to be able to pull the actual date from it. 我已经找到一种找到这些实际最大/最小值的方法,但是我似乎无法从中获取实际日期。 My code so far is like this: 到目前为止,我的代码是这样的:

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

Ideally I would like to see account num, the min or max, and then the date which this occurred on. 理想情况下,我想查看帐户编号,最小值或最大值,然后查看该日期。

Try something like this to get the min and max amount for each customer and the date it happened. 尝试这样的操作,以获取每个客户的最小和最大金额及其发生的日期。

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

If you want the data for just this year you could add a where clause to the end of the statement 如果要获取今年的数据,可以在语句末尾添加一个where子句

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

The easiest way to do this is using window/analytic functions. 最简单的方法是使用窗口/分析功能。 These are ANSI standard and most databases support them (MySQL and Access being two notable exceptions). 这些是ANSI标准,大多数数据库都支持它们(MySQL和Access是两个值得注意的例外)。

Here is one way: 这是一种方法:

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

The subquery calculates the minimum and maximum amount for each account, using min() as a window function. 子查询使用min()作为窗口函数来计算每个帐户的最小和最大金额。 The outer query selects these values. 外部查询选择这些值。 It then uses conditional aggregation to get the first date when each of those values occurred. 然后,它使用条件聚合来获取出现这些值中的每个值的第一个日期。

;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

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

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