查询以查找具有多个主要位置的所有对象

时间:2017-06-13 09:22:03

标签: sql

我有一个表对象。对象应该只有一个主要位置。我想找到所有具有多个主要位置的对象。表结构:

objectid  isprimary location
123       1         abc
456       0         sdg
789       1         jhv
789       1         dfkj

查询应显示

789      1    jhv
789      1    dfkj

基本上我想要所有isprimary为1的对象超过1个位置。

3 个答案:

答案 0 :(得分:0)

这可以使用GROUP BYHAVING条款来实现:

SELECT * FROM objects WHERE objectid IN (
    -- subquery to find ids of all objects having more than one primary location
    SELECT objectid
    FROM objects
    WHERE isprimary = 1 -- take only rows that show primary locations
    GROUP BY objectid -- "squeeze" all these rows with the same objectid to a single row
    HAVING COUNT(*) > 1 -- COUNTs number of original rows in each "squeezed" row
)

答案 1 :(得分:0)

首先限制isprimary = 1的记录,而不是objectid的记录。只返回那些有计数> 1:

select * FROM the_table WHERE objectid IN (SELECT tab2.objectid FROM the_table tab2 WHERE isprimary =1 GROUP BY  objectid HAVING COUNT(1) >1)

答案 2 :(得分:0)

如果您只想要具有多个主要位置的对象ID,则以下查询将执行此操作。

WITH data_set AS
     (SELECT 123 objectid, 1 isprimary, 'abc' loc
        FROM DUAL
      UNION
      SELECT 456 objectid, 0 isprimary, 'sdg' loc
        FROM DUAL
      UNION
      SELECT 789 objectid, 1 isprimary, 'jhv' loc
        FROM DUAL
      UNION
      SELECT 789 objectid, 1 isprimary, 'dfkj' loc
        FROM DUAL)
SELECT   objectid
    FROM data_set
   WHERE isprimary = 1
GROUP BY objectid
  HAVING COUNT (loc) > 1;

但是如果你想要记录的所有细节,那么分区将是有帮助的。

WITH DATA_SET AS
     (SELECT 123 OBJECTID, 1 ISPRIMARY, 'abc' LOC
        FROM DUAL
      UNION
      SELECT 456 OBJECTID, 0 ISPRIMARY, 'sdg' LOC
        FROM DUAL
      UNION
      SELECT 789 OBJECTID, 1 ISPRIMARY, 'jhv' LOC
        FROM DUAL
      UNION
      SELECT 789 OBJECTID, 1 ISPRIMARY, 'dfkj' LOC
        FROM DUAL),
     PROC_DATA AS
     (SELECT OBJECTID, ISPRIMARY, LOC,
             COUNT (LOC) OVER (PARTITION BY OBJECTID) AS CNT
        FROM DATA_SET
       WHERE ISPRIMARY = 1)
SELECT OBJECTID, ISPRIMARY, LOC
  FROM PROC_DATA
 WHERE CNT > 1;