2012-02-10 56 views
0

我有這樣一個表:如何在DB2中分組並獲取每個組中的第一項?

|sub_account|name|email| 
|-----------|----|-----| 
// same account and same name: email different 
|a1   |n1 |e1 | 
|a1   |n1 |e2 | 
// same account, name and email 
|a2   |n2 |e3 | 
|a2   |n2 |e3 | 

我想查詢來獲取這樣的表格:

|sub_account|name|email| 
|-----------|----|-----| 
// nothing to do here 
|a1   |n1 |e1 | 
|a1   |n1 |e2 | 
// remove the one that is exactly the same, but leave at least one 
|a2   |n2 |e3 | 

我已經試過:

select sub_account, name, first(email) 
from table 
group by sub_account, name 

但你知道「第一個」在DB2中不存在;它有什麼選擇?

感謝

回答

2
select sub_account, name, email 
from table 
group by sub_account, name, email 
+0

謝謝(我不能接受的是,僅6分鐘後) – 2012-02-10 09:30:10

1

我不知道在DB2中。在SQL服務器中,您可以針對您的問題使用DISTINCT ..您可以嘗試。

SELECT DISTINCT sub_acount, name, email 
from TABLE 
0

我找到了一種方法:

SELECT sub_account, 
     name, 
     CASE WHEN split_index=0 THEN MyList ELSE SUBSTR(MyList,1,LOCATE('|',MyList)-1) END 
FROM (select sub_account, name, LISTAGG(email,'|') as MyList, LOCATE('|',LISTAGG(LB_ARTICLE_CAISSE,'|')) AS split_index 
     from TABLE 
     group by sub_account, name) AS TABLEA 

此功能將收集您的郵件和分裂後,採取的第一個

相關問題