SQL - 如何在SQL中仅按列显示一次

时间:2017-12-10 13:52:02

标签: sql sql-server sql-server-2008

我有3列 表中的国家,州,城市。

我想要国家和州的城市名单。

我想显示单个国家/地区名称的结果,关于多个城市的州。

我按国家和州分组显示了每一行的所有国家和州。但我想要 只有一个国家名称和州名这样的

Country  State        City
--------------------------------
India    Maharashtra  Mumbai
                      Pune
                      Nagpur
         Gujrat       Surat
                      ahmedabad
USA      New york     Albany
                      New york City
         california   Los angles

2 个答案:

答案 0 :(得分:0)

你试过了吗?

SELECT DISTINCT country, state, city FROM table
GROUP BY country ASC, state ASC
ORDER BY country ASC, state ASC, city ASC;

这将仅返回每列的不同值。

答案 1 :(得分:0)

正如@Gordon所说,一旦获取数据,最好在应用程序层中执行此操作。

但如果你真的想在sql中这样做,这是一个解决方案。

;WITH All_Data AS (

    SELECT 
          COUNTRY,
          STATE,
          CITY
    FROM 
          TABLE_NAME
    GROUP BY 
          COUNTRY,
          STATE,
          CITY
--which gives all countries, states and cities.
),
Grouped_by_Country AS (

    SELECT 
          *,
           ROW_NUMBER () OVER(PARTITION BY COUNTRY ORDER BY STATE ) AS COUNTRY_NO
    FROM 
         All_Data

),
Grouped_by_State AS (

    SELECT 
          *,
          ROW_NUMBER() OVER(PARTITION BY COUNTRY,STATE ORDER BY CITY ) AS STATE_NO
    FROM 
         Grouped_by_Country

) ,

Result AS (

    SELECT 
          CASE WHEN COUNTRY_NO = 1
               THEN COUNTRY
               ELSE ''
          END AS COUNTRY,

          CASE WHEN STATE_NO = 1
               THEN STATE
               ELSE ''
          END AS STATE,

          CITY,
          COUNTRY_NO,
          STATE_NO

)

SELECT 
      COUNTRY,
      STATE,
      CITY

FROM 
      Result 
ORDER BY 
      COUNTRY_NO,
      STATE_NO