2010-06-03 92 views
1

我不能爲我的生活找出這個Sqlite語法。嵌套,分組Sqlite語法?

我們的數據庫有類似記載:

TX, Austin 
OH, Columbus 
OH, Columbus 
TX, Austin 
OH, Cleveland 
OH, Dayton 
OH, Columbus 
TX, Dallas 
TX, Houston 
TX, Austin 
(State-field and a city-field.) 

我需要的輸出是這樣的:

OH: Columbus, Cleveland, Dayton 
TX: Dallas, Houston, Austin 
(Each state listed once... and all the cities in that state... [edited: each listed once]) 

將SELECT語句(S)是什麼樣的?

回答

4

你可以使用group_concat

select state, group_concat(city) 
from YourTable 
group by state 

在回答您的意見,您可以使用distinct

select state, group_concat(distinct city) 
          ^^^^^^^^ 
+0

我什至不知道有一個group_concat()功能。 太棒了! 它列出了所有州...其次是城市(但城市一遍又一遍地重複)。 我們需要列出每個州* ONCE * ...,然後列出每個城市* ONCE *。 – Susanna 2010-06-03 19:44:55

+0

@琳達:回答編輯 – Andomar 2010-06-03 19:50:39

0

少許修改Andomar的答案似乎做的伎倆,雖然我不知道它是否真的有用:

select distinct state, group_concat(distinct city) 
from YourTable 
group by state