【问题标题】:SQL Group By Query to return the output in a desired formatSQL Group By Query 以所需格式返回输出
【发布时间】:2020-07-08 10:36:06
【问题描述】:

我有一个如下表的明细表,其中 Value 是 Int,其余列是 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 |
+------+------+--------+---------+-------+

我想写一个查询,这样我得到以下输出

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

当 2 条记录具有相同的城市、邮政、国家时,名称应该是不同的

当姓名、城市、邮政和国家相同时,姓名应为 真实姓名

如果我们有不同的城市、邮政、国家对,那么名称将是实际名称

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

向我返回出现多次的数据集(城市、邮政、国家/地区)。

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    使用带有聚合函数的case 表达式:

    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 ;
    

    【讨论】:

      【解决方案2】:

      您可以将case 表达式与count 一起使用,如下所示:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-30
        • 1970-01-01
        • 1970-01-01
        • 2020-02-08
        • 2018-01-30
        • 2017-12-23
        相关资源
        最近更新 更多