从SQL表中获取城市和国家/地区列表

时间:2009-05-21 14:28:32

标签: sql linq linq-to-sql

我有一个SQL表,在每行中我存储国家和城市的东西位置。例如:

record1, New York, USA
record2, Rome, Italy
record3, Milano, Italy
record3, Birghiman, UK 
record4, London, UK
record5, London, UK
record6, London, UK
record7, Birmingham, UK

我想生成按国家/地区和城市排序的列表,每个城市只会在结果中显示一次。

我想知道如何以优雅的方式在SQL和Linq To SQL中解决这个问题。

3 个答案:

答案 0 :(得分:9)

select distinct country, city
from <Table>
order by country, city;

答案 1 :(得分:1)

SELECT MIN(record) AS record, City, Country
FROM [MyTable]
GROUP BY City, Country
ORDER BY Country, City

答案 2 :(得分:1)

我也想到了如何用Linq做到这一点。它似乎工作正常。不确定性能

        var result = from p in table
                     group p by p.country into country_group
                     select new
                     {
                         country = country_group.Key,
                         cities = from ci in country_group
                                  group ci by ci.city into city_group
                                  select new { city = city_group.Key, cig = city_group }
                     };                          


        foreach(var co in result)
        {
            string country = co.country; 

            foreach(var ci in co.cities)
            {
                string city = ci.city;
            }
        }