Say we have a table like this:
**tablename**
ID Name Size Date AtStore1 AtStore2
1 Apple Medium 20120101 Yes
2 Pear Medium 20111231 Yes Yes
3 Lemon Small 20111231 Yes Yes
4 Orange Small 20111231 Yes
5 Carrot Medium 20111231 Yes
6 Potato Small 20111231 Yes
7 Celery Large 20111231 Yes
8 Onion Medium 20111231
9 Tomato Medium 20111231
10 Apple Medium 20111231
12 Pear Medium 20111230 Yes Yes
13 Lemon Small 20111230 Yes
14 Orange Small 20111230 Yes
15 Carrot Medium 20111230 Yes
16 Potato Small 20111230
17 Celery Large 20111229
18 Onion Medium 20111229 Yes
19 Tomato Medium 20111229
Can we construct an efficient query that retrieves ALL data per row where:
- “Yes” AtStore1 rows where there are at least 4 “Yes”es in AtStore1 on that day single day
OR (inclusive) - There is a “Yes” in AtStore2
Also acceptable is if only the first parameter is satisfied, i.e. the forward lookup of rows. I can probably script the AtStore2 part with PHP if necessary. All of my attempts have failed miserably; my attempts on how to write the question effectively in Google weren’t fruitful either.
(Answers breaking things out into different parts of code in PHP are fine too, I just want something reasonably efficient.)
For this example table, these would be the expected rows:
ID Name Size Date AtStore1 AtStore2
1 Apple Medium 20120101 Yes
2 Pear Medium 20111231 Yes Yes
3 Lemon Small 20111231 Yes Yes
4 Orange Small 20111231 Yes
5 Carrot Medium 20111231 Yes
6 Potato Small 20111231 Yes
7 Celery Large 20111231 Yes
12 Pear Medium 20111230 Yes Yes
14 Orange Small 20111230 Yes
15 Carrot Medium 20111230 Yes
18 Onion Medium 20111229 Yes
As you can see
- Jan 1 2012
-No Yeses in AtStore1
-AtStore2 has a Yes so the row is returned - Dec 31
-5 Yeses in AtStore1, so those are returned (AtStore2 Yeses in ID 2 and 3 would have sufficed as well)
-Also has ID 7 since there is a Yes in AtStore2 - The rest of the rows returned were only because of Yeses in AtStore2
Try this:
Result:
In this case null values are intentionally eliminated by an aggregate.
I’m not sure about
and t.AtStore1 = 'yes'inta on t.date = ta.date and t.AtStore1 = 'yes'remove it if you want all rows from specific day without caring whether it hasyesvalue in AtStore1 column.Added:
Answer to question from comments, but this is quick and probably dirt way to do it (lack of time):
Result: