我必須在同一查詢中執行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
添加樣本表數據和預期的結果。還要標記dbms。向我們展示您當前的查詢嘗試。 – jarlh