0

嗨,我需要有关 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';) 进行查询,但它没有工作,因为它期望同一行中的所有值和 in 运算符 ( select store from storeitem where items in ('books','stationery','toys');) ,这不遵循必须匹配所有值标准。在这方面需要你的帮助。

4

4 回答 4

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
;
于 2013-02-28T11:43:17.673 回答
2
select store
from (
  select distinct store, items
  from your_table
  where items in ('books','stationery','toys')
)
group by store
having count(0) = 3
于 2013-02-28T11:11:19.017 回答
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
于 2013-02-28T11:02:14.657 回答
0

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

从 storeitem where store 中选择 store(从 storeitem where items = 'books' 中选择 store)

并存储在(从 item ='toys' 的 storeitem 中选择存储)

并存储在(从 item='stationairy' 的 storeitem 中选择存储)

于 2013-02-28T12:05:16.937 回答