-1

我有一个庞大的数据库,其中包含超过 400 万行,如下所示:

Customer ID Shop 
1           Asda 
1           Sainsbury
1           Tesco 
2           TEsco 
2           Tesco

我需要计算过去 4 周内在 Tesco Sainsbury 和 Asda 的所有 3 家商店购物的顾客。如果可以用子查询来做,你能建议吗?

4

1 回答 1

0

这是“set-within-sets”子查询的一个示例。您可以通过聚合解决它:

select customer_id
from Yourtable t
where <shopping date within last four weeks>
group by customer_id
having sum(case when shop = 'Asda' then 1 else 0 end) > 0 and
       sum(case when shop = 'Sainsbury' then 1 else 0 end) > 0 and
       sum(case when shop = 'Tesco' then 1 else 0 end) > 0;

这种结构非常灵活。因此,如果您想要 Asda 和 Tesco 而不是 Sainsbury,那么您会这样做:

select customer_id
from Yourtable t
where <shopping date within last four weeks>
group by customer_id
having sum(case when shop = 'Asda' then 1 else 0 end) > 0 and
       sum(case when shop = 'Sainsbury' then 1 else 0 end) = 0 and
       sum(case when shop = 'Tesco' then 1 else 0 end) > 0;

编辑:

如果您想要计数,则将其用作子查询并计算结果:

select count(*)
from (select customer_id
      from Yourtable t
      where <shopping date within last four weeks>
      group by customer_id
      having sum(case when shop = 'Asda' then 1 else 0 end) > 0 and
             sum(case when shop = 'Sainsbury' then 1 else 0 end) > 0 and
             sum(case when shop = 'Tesco' then 1 else 0 end) > 0
     ) t
于 2013-07-04T19:46:46.477 回答