简体   繁体   中英

SQL Group By Query to return the output in a desired format

I have a table detailtable like below where Value is Int and rest of the column are Varchar

+------+------+--------+---------+-------+
| Name | City | postal | country | value |
+------+------+--------+---------+-------+
| Adam | hyd  | 500000 | India   |    10 |
| eve  | hyd  | 500000 | India   |    20 |
| Adam | Aus  | 200000 | India   |    30 |
| Adam | Aus  | 200000 | India   |    40 |
| Scott| Aus  | 400000 | India   |    90 |
+------+------+--------+---------+-------+

I want to write a Query such that i get the following output

+---------+------+--------+---------+
|  Name   | City | postal | country |
+---------+------+--------+---------+
| Various | hyd  | 500000 | India   |
| Adam    | Aus  | 200000 | India   |
| Scott   | Aus  | 400000 | India   | 
+---------+------+--------+---------+

When 2 records have same city, postal,country, Name should be Various

and when Name, city, postal and country are same then name should be actual name

In case we have distinct city, postal, country pair then name will be actual name

select City,Postal,country from detailtable group by City,Postal,country having count(*)>1

returns me the data set (City,Postal,country) which are having more than one occurance.

Use a case expression with aggregation functions:

select (case when min(name) = max(name) then min(name)
             else 'various'
        end) as name, City, Postal, country
from detailtable
group by City, Postal, country ;

You can use the case expression with count as follows:

select  count(distinct name) = 1 then min(name) else 'various' end as name, 
        city, postal, country
from detailtable t
group by City, Postal, country;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM