Oracle Sql查询Group by Clause

时间:2012-03-31 21:33:46

标签: sql oracle group-by

MY_TABLE =有2列数字,城市的表。
期望输出=城市和与城市相关联的唯一号码数。西雅图,Bellevue是Combined的一部分。即使有4个数字与西雅图相关联,Bellevue的输出也是3,因为只有3个不同的数字 - 123,456,786。

  MY_TABLE
Number   City
123  Seattle
456  Bellevue
789  LosAngeles
780  LosAngeles
123  Bellevue
786  Bellevue

期望的输出:

Combined 3
LosAngeles 2

到目前为止的查询:

SELECT NUMBER, CITY FROM MY_TABLE WHERE LOOKUP_ID=100 AND CITY IN 
('Seattle', 'Bellevue', 'LosAngeles')
GROUP BY NUMBER, CITY

如果有人提出相同的建议,我们将非常感激。

4 个答案:

答案 0 :(得分:3)

您可以执行类似

的操作
SELECT (case when city IN ('Seattle', 'Bellevue') 
             then 'Combined'
             else city
          end) city,
       count( distinct number ) 
  FROM my_table
 WHERE lookup_id = 100
   AND city IN ('Seattle', 'Bellevue', 'LosAngeles')
 GROUP BY (case when city IN ('Seattle', 'Bellevue') 
                then 'Combined'
                else city
           end) 

当然,我的猜测是你有一些其他的表可以告诉你需要合并哪些CITY值,而不是使用硬编码的CASE语句。

答案 1 :(得分:2)

with t as (
SELECT (
        case when city IN ('Seattle', 'Bellevue') 
        then 'Combined'
        else city
        end
    ) city, number from my_table
)
select city, count(distinct number) from t
group by city

请告诉我,如果它有用

答案 2 :(得分:1)

试试这个:

SELECT 
  (CASE CITY
  WHEN 'Seattle' THEN ‘Combined’ 
  WHEN 'Bellevue' THEN ‘Combined’ 
  ELSE CITY 
  END), COUNT(*) 
FROM 
  MY_TABLE 
WHERE 
  LOOKUP_ID=100 AND CITY IN ('Seattle', 'Bellevue', 'LosAngeles') 
GROUP BY 
   NUMBER, 
   (CASE CITY
    WHEN 'Seattle' THEN ‘Combined’ 
    WHEN 'Bellevue' THEN ‘Combined’ 
    ELSE CITY 
    END) 

应该按照你的要求做,但我怀疑你有一些其他的表,你可以定义哪些城市应该被认为是相同的,在这种情况下,你需要加入这些表

答案 3 :(得分:1)

已有3个答案,其中没有一个是更多城市的通用答案。 试试这个:

SELECT City, COUNT(Number) AS ExclusiveNumbers
FROM (SELECT q2.City, q2.CityNumCount, b.Number
      FROM MY_Table b INNER JOIN
           (SELECT c.City, MAX(NumOccurs) AS CityNumCount
            FROM My_Table c INNER JOIN
                             (SELECT Number, COUNT(City) AS NumOccurs
                              FROM My_Table
                              GROUP BY Number) q1 ON c.Number = q1.Number
            GROUP BY c.City) q2 ON b.City = q2.City) q3
WHERE CityNumCount = 1
GROUP BY City
UNION
SELECT 'Combined', COUNT(DISTINCT Number)
FROM (SELECT q2.City, q2.CityNumCount, b.Number
      FROM MY_Table b INNER JOIN
           (SELECT c.City, MAX(NumOccurs) AS CityNumCount
            FROM My_Table c INNER JOIN
                             (SELECT Number, COUNT(City) AS NumOccurs
                              FROM My_Table
                              GROUP BY Number) q1 ON c.Number = q1.Number
            GROUP BY c.City) q2 ON b.City = q2.City) q3
WHERE CityNumCount > 1

工会的上半部分为每个与任何其他城市没有共同号码的城市名称,它有多少不同的数字。
下半部分计算出与其他城市有共同数字的城市的不同数字。这两个数字总是与原始表中不同数字的数量相加。