2010-06-03 90 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