Попробуйте это:
select t.*
from tablename t
join (
select date
from tablename
where AtStore1='yes'
group by date
having count(*) >= 4
) ta on t.date = ta.date and t.AtStore1 = 'yes'
union
select *
from tablename
where AtStore2 = 'yes'
Результат:
ID Name Size Date AtStore1 AtStore2
1 Apple Medium 2012-01-01 00:00:00.000 NULL Yes
2 Pear Medium 2011-12-31 00:00:00.000 Yes Yes
3 Lemon Small 2011-12-31 00:00:00.000 Yes Yes
4 Orange Small 2011-12-31 00:00:00.000 Yes NULL
5 Carrot Medium 2011-12-31 00:00:00.000 Yes NULL
6 Potato Small 2011-12-31 00:00:00.000 Yes NULL
7 Celery Large 2011-12-31 00:00:00.000 NULL Yes
12 Pear Medium 2011-12-30 00:00:00.000 Yes Yes
14 Orange Small 2011-12-30 00:00:00.000 NULL Yes
15 Carrot Medium 2011-12-30 00:00:00.000 NULL Yes
18 Onion Medium 2011-12-29 00:00:00.000 NULL Yes
В этом случае нулевые значения намеренно исключаются из совокупности.
Я не уверен, что and t.AtStore1 = 'yes'
в ta on t.date = ta.date and t.AtStore1 = 'yes'
удалите его, если вы хотите, чтобы все строки имели определенный день, не заботясь о том, имеет ли оно значение yes
в столбце AtStore1.
Добавлена
Ответ на вопрос из комментариев, но это быстрый и, вероятно, грязный способ сделать это (нехватка времени):
select t3.*, t4.qty from tablename t3
join (
select id, max(qty) as qty from (
select t.id, ta.qty
from tablename t
join (
select date, count(*) as qty
from tablename
where AtStore1='yes'
group by date
having count(*) >= 4
) ta on t.date = ta.date and t.AtStore1 = 'yes'
union
select id, 0 as src
from tablename
where AtStore2 = 'yes'
) t2
group by t2.id
) t4 on t3.id = t4.id
Результат:
ID Name Size Date AtStore1 AtStore2 qty
1 Apple Medium 2012-01-01 00:00:00.000 NULL Yes 0
2 Pear Medium 2011-12-31 00:00:00.000 Yes Yes 5
3 Lemon Small 2011-12-31 00:00:00.000 Yes Yes 5
4 Orange Small 2011-12-31 00:00:00.000 Yes NULL 5
5 Carrot Medium 2011-12-31 00:00:00.000 Yes NULL 5
6 Potato Small 2011-12-31 00:00:00.000 Yes NULL 5
7 Celery Large 2011-12-31 00:00:00.000 NULL Yes 0
12 Pear Medium 2011-12-30 00:00:00.000 Yes Yes 0
14 Orange Small 2011-12-30 00:00:00.000 NULL Yes 0
15 Carrot Medium 2011-12-30 00:00:00.000 NULL Yes 0
18 Onion Medium 2011-12-29 00:00:00.000 NULL Yes 0