简体   繁体   中英

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 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).

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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