0

考虑下表Orders

OrderID  Name    Amount
-----------------------
 1       A          100
 2       A            5
 3       B           32
 4       C         4000
 5       D          701
 6       E           32
 7       F          200
 8       G          100
 9       H           12
10       I           17
11       J          100
12       J          100
13       J           11
14       A            5

对于每个唯一的“金额”,我需要确定是否有 2 个或更多用户订购了该确切金额,然后列出这些订单的详细信息。所以所需的输出将是:

OrderID  Name  Amount
---------------------
 1       A        100
 8       G        100
11       J        100
12       J        100
 3       B         32
 6       E         32
  • 请注意,用户A订购了 2 x 5(order214)的订单,但这不应该出现在输出中,因为它在同一个用户中。只有当另一个用户下订单时5,它才应该在输出中。

谁能帮我吗?

4

3 回答 3

2

我只会使用exists

select o.*
from orders o
where exists (select 1
              from orders o2
              where o2.amount = o.amount and o2.name <> o.name
             );
于 2018-08-13T10:32:00.517 回答
2

你可以做 :

select t.*
from table t
where exists (select 1 from table t1 where t1.amount = t.amount and t1.name <> t.name);
于 2018-08-13T10:32:07.697 回答
1

如果您只想要选定的字段,那么

    SELECT Amount,name,
     count(*) AS c
    FROM TABLE
    GROUP BY Amount, name
    HAVING c > 1
    ORDER BY c DESC

如果你想要整行

select * from table where Amount in (
  select Amount, name from table
  group by Amount, name having count(*) > 1)
于 2018-08-13T10:38:03.157 回答