难以理解这个查询oracle sql

时间:2013-08-13 06:15:33

标签: sql oracle subquery

我只想知道此查询的内部执行,尤其是如何使用子查询中的值

SELECT bu, location FROM 
( 
    SELECT DISTINCT bu, hqname, location FROM DOCTOR 
    UNION 
    SELECT DISTINCT bu, hqname, location FROM CHEMIST 
    UNION 
    SELECT DISTINCT bu, hqname, location FROM STOCKIST
) 
GROUP BY bu, location 
HAVING COUNT (DISTINCT hqname) > 1;

4 个答案:

答案 0 :(得分:3)

评论SQL

  SELECT -- bu and location from doctors, chemists and stockists 
         -- (see inner query)  
         bu, 
         location
    FROM ( -- All doctors, chemists and stockists 
           -- with duplicates removed: 
           -- e.g. if a person is a chemist and a doctor, only one record is preserved
          SELECT DISTINCT bu, 
                          hqname, 
                          location 
                     FROM DOCTOR
           UNION
          SELECT DISTINCT bu, 
                          hqname, 
                          location 
                     FROM CHEMIST
           UNION
          SELECT DISTINCT bu, 
                          hqname, 
                          location 
                     FROM STOCKIST)
GROUP BY -- combining "bu" and "location" (for HAVING)
         bu, 
         location
         -- choose these records only that have more than one hqName
         -- for the same bu and location, e.g. 
         -- hqName bu loc
         --      x  1   2
         --      x  1   2 <-- second hqName ("x") for the same bu and loc (1, 2)
  HAVING COUNT (DISTINCT hqname) > 1;

答案 1 :(得分:1)

子查询返回bu, hqname, location

的唯一组合

然后将它们分组,并且只保留有多个名称的位置。

答案 2 :(得分:0)

在下面的查询中,使用UNION将三个表'DOCTOR','CHEMIST'和'STOCKIST'的结果合并为一个结果(视为表格)

    SELECT DISTINCT bu, hqname, location FROM DOCTOR 
    UNION 
    SELECT DISTINCT bu, hqname, location FROM CHEMIST 
    UNION 
    SELECT DISTINCT bu, hqname, location FROM STOCKIST

使用GROUP BY获取聚合数据,其数量为hqname&gt;每一个1 (bu,location)组如下

GROUP BY bu, location 
HAVING COUNT (DISTINCT hqname) > 1;

最后,您将从结果集中获得唯一的bu,location 简单地说就是

SELECT  bu, location FROM Resultset
GROUP BY bu, location 
HAVING COUNT (DISTINCT hqname) > 1;

答案 3 :(得分:0)

尝试此查询而不使用返回相同结果的DISTINCT -

SELECT bu, location
FROM (  
    SELECT bu, hqname, location FROM DOCTOR
    UNION
    SELECT bu, hqname, location FROM CHEMIST
    UNION
    SELECT bu, hqname, location FROM STOCKIST
) AS t
GROUP BY bu, location
HAVING COUNT (DISTINCT hqname) > 1