0

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

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

4 回答 4

3

Commented 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;
于 2013-08-13T06:29:18.810 回答
1

子查询返回唯一的组合bu, hqname, location

然后将它们分组,仅保留有多个 hqname 的位置。

于 2013-08-13T06:26:16.413 回答
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 获取聚合数据,每个 (bu, location) 组的 hqname > 1 计数如下

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

最后,您将从结果集中获得唯一的 bu,位置,简单地说为

SELECT  bu, location FROM Resultset
GROUP BY bu, location 
HAVING COUNT (DISTINCT hqname) > 1;
于 2013-08-13T06:23:17.603 回答
0

DISTINCT在不使用which 返回相同结果的情况下尝试此查询-

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
于 2013-08-13T06:24:42.800 回答