简体   繁体   中英

SQL aggregate function query selecting multiple columns

I am trying to query the table below, which is a very basic version of my actual table,

ID   SaleDate     Amount
1   2014-09-01     50
1   2014-10-01     20
1   2014-11-01     10
2   2013-11-01     10
2   2013-12-01     20
2   2014-01-01     25

to get an output like

Output

ID   MinDate       MaxDate    StartAmount  EndAmount
1   2014-09-01   2014-11-01     50           10
2   2013-11-01   2014-01-01     10           25

The SaleDate is always increasing. But the amount may vary. I picked up the min and max dates for each ID. That is the easy part. But, I also want the amount that is on the SaleDate.

I tried using this

Select x.ID,min(x.SaleDate) MinDate, x.Amount StartAmount, max(y.SaleDate) MaxDate,y.Amount EndAmount
From Sales x Join Sales y
On x.ID = y.ID
Group By x.ID,y.ID,x.Amount,y.Amount
Order By x.ID

But I am sure I should not be using the Amount field in the group by function. Is there a similar question in SO that answers this type of situation ? Or if there is an easy solution just point me that way. I don't need the direct answer just a general method to deal with such cases.

Most databases support the ANSI standard window and ranking functions. You can do this using row_number() and conditional aggregation:

select s.id, min(saledate) as MinDate, max(saledate) as MaxDate,
       max(case when seqnum = 1 then amount end) as StartAmount,
       max(case when seqnum = cnt then amount end) as EndAmount
from (select s.*, row_number() over (partition by s.id order by s.saledate) as seqnum,
             count(*) over (partition by s.id) as cnt
      from sales s
     ) s
group by s.id;

you need to do it in two steps. first, the easy part, then take those results and join back on the original table using your min/max value to look up the value from the related column.

    select id, mindate, maxdate, 
           s_min.amount as startamount, s_max.amount as endamount 
    from (
    Select ID,min(SaleDate) MinDate, max(SaleDate) MaxDate
    From Sales s
    Group By ID
    ) d inner join sales s_min on d.mindate = s.saledate and d.id = s.id
    inner join sales s_max on d.maxdate = s.saledate and d.id = s.id

are you really joining the same table twice?

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