从3行收集的sql子查询

时间:2013-07-04 19:35:51

标签: sql subquery

我有一个庞大的数据库,有超过400万行,看起来像这样:

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

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

1 个答案:

答案 0 :(得分: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