假设有一张表,结构如下:
Nmae Date Fruit
小明 2021/10/10 苹果
小明 2021/10/10 香蕉
小明 2021/10/10 葡萄
小明 2021/10/22 雪梨
小明 2021/10/11 樱桃
小明 2021/10/10 香蕉
小明 2022/10/20 水蜜桃
小红 2021/10/20 苹果
小红 2021/10/21 雪梨
小红 2021/10/22 香蕉
小红 2021/10/21 香蕉
小红 2021/10/20 水蜜桃
小红 2021/10/21 葡萄
小刚 2021/10/25 香蕉
小刚 2021/10/21 苹果
小刚 2021/10/25 水蜜桃
小刚 2021/10/25 葡萄
小刚 2021/10/21 香蕉
现在有一个业务需求,需求概括起来就是需要用SQL筛选出同一个Date里面吃了“苹果、雪梨、葡萄、香蕉”当中两种或以上的人员姓名,并输出以下表结构:
Name Date Fruit_1 Fruit_2 Frute_3 Frute_4
我个人思路是:
with a as
(select t.name, t.date, t.frute
from table t
where t.frute in ('苹果', '雪梨', '葡萄', '香蕉')),
b as
(select a.name, a.date, a.frute frute_1, t2.frute frute_2
from a
join table t2
on a.date = t2.date
and a.name = t2.name
and t2.frute != t1.frute
and t2.frute in ('苹果', '雪梨', '葡萄', '香蕉')),
c as
(select b.name, b.date, b.frute_1, b.frute_2, t3.frute frute_3
from b
left join table t3
on b.date = t3.date
and t3.name = b.name
and t3.frute != b.frute_1
and t3.fruit != frute_2
and t3.frute in ('苹果', '雪梨', '葡萄', '香蕉')),
d as
(select c.name, c.date, c.frute_1, c.frute_2, c.frute_3, c.frute frute_4
from c
left join table t4
on c.date = t4.date
and t4.name = c.name
and t4.frute != c.frute_1
and t4.fruit != c.frute_2
and t4.frute != c.frute_3
and t4.frute in ('苹果', '雪梨', '葡萄', '香蕉'))
select * from c
如果在原表结构右边再新增一列num,表示每天吃的水果种类的对应数量,输出时候也需要将这个每天吃的水果种类的对应数量一并输出,SQL语句该怎么去改写呢?
我感觉我的思路好复杂且有错,真正执行在业务几千万行的大表也会很慢,请教各位这个需求的SQL如何写才更好吗?