按城市名称分组,仅在第一行显示相同的城市名称

时间:2016-07-30 10:12:40

标签: mysql sql group-by

我有一张桌子

city|locality
a   |  bc
a   |  dc
a   |  ef
a   |  gh
a   |  ij

我想创建一个组,以便显示

a |bc
  |dc
  |ef
  |gh
  |ij

我正在使用

select(*) from 'tablename' group by city;

但它只给我一个地方价值。

4 个答案:

答案 0 :(得分:1)

不确定这是否是您想要的,但是如果您希望在一个新单元格中获取locality的{​​{1}}的所有行,则可以使用此功能。

a

这将输出:

SELECT *, GROUP_CONCAT(locality) as localities FROM table GROUP BY city

答案 1 :(得分:1)

解决方案就是使用:

select city, locality from yourtable order by city, locality

如果值发生变化,您只需打印/使用city即可解决表示层中的问题。

像(在Java中):

String previousCity = null;
while (rs.next()) {
    String currentCity = rs.getString("city");
    if (Objects.equals(previousCity, currentCity) {
        // Same as previous: no need to print so set blank
        String currentCity = "";
    } else {
        previousCity = currentCity;
    }

    System.out.println(currentCity + " | " + rs.getString("locality"));
}

答案 2 :(得分:0)

试试这个,

select col1, GROUP_CONCAT(col2 SEPARATOR ';') from tablename;

它将为您提供如下结果:

a | BC;直流电; EF; GH; IJ

现在以自己的方式使用它。

答案 3 :(得分:-1)

您可以尝试编写2个查询,

select distinct (city) from 'tablename';

那么你将把城市作为' a';

select * from tablename where city='a';// 'a' means out put of first query