简体   繁体   English

SQL聚合函数查询选择多个列

[英]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. SaleDate一直在增加。 But the amount may vary. 但是数量可能会有所不同。 I picked up the min and max dates for each ID. 我为每个ID设置了最小和最大日期。 That is the easy part. 那是容易的部分。 But, I also want the amount that is on the SaleDate. 但是,我也想要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 ? SO中是否有类似的问题可以回答这种情况? 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. 大多数数据库都支持ANSI标准窗口和排名功能。 You can do this using row_number() and conditional aggregation: 您可以使用row_number()和条件聚合来做到这一点:

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? 您是否真的两次参加了同一张桌子?

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

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