2013-11-27 61 views
0

我有一個表,看起來像這樣在Oracle DB:排序由最大值

TransactionID  Customer_id  Sequence  Activity 
----------   -------------  ----------  ----------- 
1     85    1    Forms 
2     51    2    Factory 
3     51    1    Forms 
4     51    3    Listing 
5     321    1    Forms 
6     321    2    Forms 
7     28    1    Text 
8     74    1    Escalate 

而且我希望能夠理清所有行sequence最高爲每customer_id。 我有一個MAX()函數我可以使用的順序,但基於customer_id莫名其妙?

我想查詢的結果是這樣的:

TransactionID  Customer_id  Sequence  Activity 
----------   -------------  ----------  ----------- 
1     85    1    Forms 
4     51    3    Listing 
6     321    2    Forms 
7     28    1    Text 
8     74    1    Escalate 
+0

只是使用'MAX(),那麼組by' .. –

回答

2
select t1.* 
from your_table t1 
inner join 
(
    select customer_id, max(Sequence) mseq 
    from your_table 
    group by customer_id 

) t2 on t1.customer_id = t2.customer_id and t1.sequence = t2.mseq 
+0

這是最好的解決方案,因爲它可以讓你得到正確的transactionID。在GROUP BY中使用MAX將強制您從結果中排除TransactionID。 – Tobberoth

+0

工作就像一個魅力,感謝Tobberoth! – user1988591

0

SQL Fiddle

的Oracle 11g R2架構設置

CREATE TABLE tbl (TransactionID, Customer_id, Sequence, Activity) AS 
      SELECT 1, 85, 1, 'Forms' FROM DUAL 
UNION ALL SELECT 2, 51, 2, 'Factory' FROM DUAL 
UNION ALL SELECT 3, 51, 1, 'Forms' FROM DUAL 
UNION ALL SELECT 4, 51, 3, 'Listing' FROM DUAL 
UNION ALL SELECT 5, 321, 1, 'Forms' FROM DUAL 
UNION ALL SELECT 6, 321, 2, 'Forms' FROM DUAL 
UNION ALL SELECT 7, 28, 1, 'Text' FROM DUAL 
UNION ALL SELECT 8, 74, 1, 'Escalate' FROM DUAL; 

查詢1

SELECT 
    MAX(TransactionID) KEEP (DENSE_RANK LAST ORDER BY Sequence) AS TransactionID, 
    Customer_ID, 
    MAX(Sequence) KEEP (DENSE_RANK LAST ORDER BY Sequence) AS Sequence, 
    MAX(Activity) KEEP (DENSE_RANK LAST ORDER BY Sequence) AS Activity 
FROM tbl 
GROUP BY Customer_ID 
ORDER BY TransactionID 

Results

| TRANSACTIONID | CUSTOMER_ID | SEQUENCE | ACTIVITY | 
|---------------|-------------|----------|----------| 
|    1 |   85 |  1 | Forms | 
|    4 |   51 |  3 | Listing | 
|    6 |   321 |  2 | Forms | 
|    7 |   28 |  1 |  Text | 
|    8 |   74 |  1 | Escalate | 
0

請試試吧

with cte as 
(
    select Customer_id,MAX(Sequence) as p from Tablename group by Customer_id 
) 
select b.* from cte a join Tablename b on a.p = b.Sequence where a.p = b.Sequence and a.Customer_id=b.Customer_id order by b.TransactionID