查询以获取跨数据库行匹配多个值的数据

时间:2013-02-28 10:52:30

标签: sql oracle

您好我需要有关SQL查询的帮助。结果必须匹配跨行的单个列的值。这是一个例子。我需要找到必须拥有所有这些待售商品的商店:书籍,文具和玩具。

Store Items
----- --------
AA     PERFUMES
AA     TOYS
BB     STATIONERY
BB     BOOKS
BB     TOYS

在上面的示例中,“BB”是唯一符合我们所有条件的商店,因此也就是查询所期望的结果。

我尝试使用AND运算符(select store from storeitem where items = 'books' and items ='toys' and items='stationery';)进行查询,但它没有工作,因为它期望同一行中的所有值和运算符(select store from storeitem where items in ('books','stationery','toys');)中的所有值,这不符合必须匹配所有价值标准。 需要你的帮助。

4 个答案:

答案 0 :(得分:3)

您可以完全跳过子查询并使用HAVING DISTINCT子句返回所需的商店。

SELECT  store, COUNT(*)
FROM    your_table
WHERE   items in ('STATIONAIRY', 'BOOKS', 'TOYS')
GROUP BY
        store
HAVING  COUNT(DISTINCT items) = 3
;

示例

WITH your_table as (
  SELECT 'AA' as Store, 'PERFUMES' as Items FROM dual UNION ALL
  SELECT 'AA', 'TOYS' FROM dual UNION ALL
  SELECT 'BB', 'STATIONAIRY' FROM dual UNION ALL
  SELECT 'BB', 'BOOKS' FROM dual UNION ALL
  SELECT 'BB', 'TOYS' FROM dual
)
SELECT  store, COUNT(*)
FROM    your_table
WHERE   items in ('STATIONAIRY', 'BOOKS', 'TOYS')
GROUP BY
        store
HAVING  COUNT(DISTINCT items) = 3
;

答案 1 :(得分:2)

select store
from (
  select distinct store, items
  from your_table
  where items in ('books','stationery','toys')
)
group by store
having count(0) = 3

答案 2 :(得分:1)

这是应该工作的一般方法(未经Oracle专门测试):

select store from (
  select store,
         max(case when items = 'stationery' then 1 else 0 end) as has_stationery,
         max(case when items = 'books'      then 1 else 0 end) as has_books,
         max(case when items = 'toys'       then 1 else 0 end) as has_toys
    from your_table
    group by store
  ) as stores_by_item
  where has_stationery = 1 and has_books = 1 and has_toys = 1

答案 3 :(得分:0)

如果我正确理解您的问题,您需要该查询:

从storeitem中选择商店,其中存储(从商店中选择商店,其中items ='books')

并存储(从商店中选择商店,其中items ='toys')

AND存储(从storeitem选择商店,其中items ='stationairy')