2016-08-12 65 views
0

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

更新:

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

输入:表Share_history和表Customer和表分享和表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和计数(无次特定份额被买(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

添加样本表数据和预期的结果。还要标记dbms。向我们展示您当前的查询尝试。 – jarlh

回答

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 

休息我想你可以添加。

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; 
相关问题