[英]SQL - how to display group by columns only once in SQL
I have 3 columns Country, state, city in table. 我在表中有3列国家,州,城市。
I want city list with country and state. 我想要国家和州的城市清单。
I want to display result like single country name, with respect to state with multiple cities. 我想针对多个城市的州显示类似单个国家名称的结果。
I did group by on country and state which display all country and state in each row. 我按国家和州分组,每行显示所有国家和州。 but I want only single country name and state name like this
但我只想要这样一个国家名和州名
Country State City
--------------------------------
India Maharashtra Mumbai
Pune
Nagpur
Gujrat Surat
ahmedabad
USA New york Albany
New york City
california Los angles
Have you tried: 你有没有尝试过:
SELECT DISTINCT country, state, city FROM table
GROUP BY country ASC, state ASC
ORDER BY country ASC, state ASC, city ASC;
That would return only distinct values from each column. 那将只返回每列中不同的值。
As @Gordon said it is better to do this in application layer once you fetched the data. 正如@Gordon所说的那样,一旦您获取了数据,最好在应用程序层中执行此操作。
But if you really want to do this in sql, here is one solution. 但是,如果您真的想在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.