2
products purchased
--------------------------
bana
bana
bana
stra
kiwi

reward requirements table (related to a rewards table)
reward id, products
----------------------
1,bana
1,bana
1,bana
2,stra
2,bana
3,stra
4,cart
5,bana
5,bana
5,oliv

你能帮我用sql来获得购买的产品有资格获得的奖励吗?

在上述情况下,奖励 ID 为:

1
2
3

如果有更好的设计可以使解决方案更容易,我也欢迎这些。我希望使用产品名称是为了更容易解释。(稍后我将替换为产品 ID)

4

2 回答 2

4

此查询将解决您的问题。

select r.reward_id
from (
  select reward_id, product, count(*) needed
  from reward_requirements
  group by reward_id, product
) r
left join (
  select product, count(*) bought
  from products_purchased
  group by product 
) p on r.product=p.product and p.bought >= r.needed
group by r.reward_id
having count(reward_id) = count(distinct p.product)
order by r.reward_id

为了使您的设计更好,您可以重做reward_requirements 以获得列(产品,需要),而不必多次列出它。它还将摆脱第一个子查询。

于 2012-10-07T05:44:40.640 回答
2

使用此架构:

CREATE TABLE            product
(
    product_id          int IDENTITY
    , name              varchar(50)
)

CREATE TABLE            requirement
(
    requirement_id      int IDENTITY
    , product_id        int
    , quantity          int
    , reward_id         int
)

CREATE TABLE            reward
(
    reward_id           int IDENTITY
    , reward            varchar(50)
)

CREATE TABLE            purchased
(
    purchased_id        int IDENTITY
    , product_id        int
    , quantity          int
)

您的查询变为:

SELECT      requirement.reward_id
FROM        requirement
            LEFT JOIN purchased
                ON  purchased.product_id = requirement.product_id
                AND purchased.quantity >= requirement.quantity
GROUP BY    requirement.reward_id
HAVING      COUNT(purchased.product_id) = COUNT(requirement.reward_id);

这是一个可以玩的 SQLFiddle:http ://sqlfiddle.com/#!3/e93c9/7

于 2012-10-07T19:28:04.157 回答