在一个查询中计算和最大聚合函数在同一个表中

时间:2016-08-12 09:01:16

标签: sql

我必须在同一个查询中执行count和max aggregate函数。例如,我有历史表包含日期列。我需要检索最新日期以及使用某些条件计数()。标准仅适用于计数()。我能够使用max和rank函数检索最新日期。但是无法合并两者。你能帮忙吗?

更新

场景:客户购买/出售股票。

输入:表Share_history和表Customer和Table Share以及Table Share_Status

客户:

Cust_id    |Cust_name            
    1      |A        
    2      |B       

分享:

Share_id|Share_Name|Owner|  
10      |ABC       |XYZ  |  
20      |BCD       |MNC  | 

Share_Status:

Share_Status_Id|Share_Status_Name  
1              |Buy  
2              |Sell

Share_history:

Share_history _id|Share_id|Trans_date|Share_status_Id|Cust_id  
100              |10       |12/12/14 | 1             |1   
101              |10       |24/12/14 | 2             |1    
102              |10       |14/01/15 | 1             |1   
103              |10       |28/02/15 | 2             |1    
103              |10       |16/03/15 | 1             |1 

输出:最新的Trans_date和count(特定份额的购买次数(1))和Cust_id = 1。

查询:

select share1.Share_id,SHAREHIST.Latest_Date,SHAREHIST.buycount
from Share share1 left outer join
     (select share_id,max(Trans_date) keep(dense_rank last order by share_id) as Latest_Date,
             (select count(*) as buycount from Share_history where Share_status_id=1 and Share_id=share1.Share_id)
      from Share_history
      group by Share_id
     ) SHAREHIST 
     on SHAREHIST.share_id=share1.share_id

预期:

Share_id|Latest_Date|buycount       
10      |16/03/15  | 3       

2 个答案:

答案 0 :(得分:0)

尝试使用:

SELECT 
    Share_id
    ,Trans_Date
    ,COUNT(Share_id) buycount
FROM 
(
    SELECT 
        * 
    FROM Share_history SH 
    WHERE Trans_Date = (SELECT MAX(Trans_Date) FROM Share_history)
) SH
GROUP BY Share_id, Trans_Date

我认为你可以添加的其他联接。

答案 1 :(得分:0)

我想你只想要聚合:

select sh.share_id, max(trans_date) as trans_date, count(*) as buy_count,
from share_history sh
where cust_id = 1
group by sh.share_id;