7

我有一张名为 measure 的测量。该表有一列表示位置,另一列表示对应的(示例已简化)。

该表看起来像(注loc1的 2 个条目):

location | value
-----------------
loc1     | value1
loc1     | value2
loc2     | value3
loc3     | value4
loc4     | value5

我现在想制定一个 SQL 查询(实际上我使用 sqlite),它只返回表的前两行(即 loc+value1 和 loc1+value2),因为这个位置在这个表中有多个条目。

伪文本公式是:向我显示位置的行,它们在整个表中出现
多次伪代码:

SELECT * from measures WHERE COUNT(location over the whole table) > 1

解决方案可能真的很简单,但不知何故我似乎没有破解坚果。

到目前为止,我有一个 SELECT 语句,它返回具有多个条目的位置。作为下一步,我将需要与从该查询返回的位置相对应的所有行:

SELECT location FROM measures GROUP BY location HAVING count(*) > 1

因此,下一步我尝试使用同一个表进行 JOIN 并合并上述查询,但结果不正确。我试过这样,但这是错误的:

select t1.location, t1.value
from 
     measures as t1
     join 
     measures as t2 on t1.location = t2.location 
group by
      t2.location 
having count(*) > 1

帮助表示赞赏!

4

4 回答 4

8

你是正确的使用HAVING,并考虑使用自连接......只是操作的顺序略有偏差......

select m1.location, m1.value
from measures m1
join (
  select location
  from measures
  group by location
  having count(*) > 1
) m2 on m2.location = m1.location

子选择获取具有多个条目的所有位置......然后再次将其加入表以获得完整结果。

SQL小提琴

于 2013-08-07T16:00:09.313 回答
5

使用嵌套选择:

SELECT location,value,type,value_added
  FROM measures
  WHERE location IN
    (SELECT location FROM measures
      GROUP BY location HAVING COUNT(*)>1)

(语法是凭记忆的,可能有点不对)

于 2013-08-07T16:00:18.280 回答
2

这个想法是获取具有多个值的位置列表。以下用于in获取记录:

select m.*
from measures m
where m.location in (select location from measures group by location having count(*) > 1);

你也可以用一个连接来制定这个:

select m.*, mdup.numdups
from measures m join
     (select location, count(*) as numdups
      from measures
      group by location
      having count(*) > 1
     ) mdup
     on m.location = mdup.location;

以这种方式进行查询的一个优点是您可以获得重复项的数量。

于 2013-08-07T16:00:05.730 回答
1
SELECT * FROM measures WHERE
(location) IN (
    SELECT
        location
    FROM
        measures
    GROUP BY
        location
    HAVING
        COUNT(location) > 1
) ORDER BY ASC
于 2013-08-07T16:09:38.263 回答