0

在一个唯一的表中,我有多行具有相同的参考信息 ( ID)。对于相同的day,客户有drink并且Appreciation是 1(是)或 0(否)。

Table 
ID   DAY Drink   Appreciation
1    1   Coffee   1
1    1   Tea      0
1    1   Soda     1
2    1   Coffee   1
2    1   Tea      1
3    1   Coffee   0
3    1   Tea      0
3    1   Iced Tea 1

我首先尝试看看谁欣赏某种饮料,这显然很简单

Select ID, max(appreciation)
from table 
where (day=1 and drink='coffee' and appreciation=1) 
or (day=1 and drink='tea' and appreciation=1)

由于我什至对饮料都不感兴趣,所以我过去常常max删除重复项,只保留评价最高的车道。

但我现在想做的是看看谁实际上欣赏他们所喝的每一杯。再说一次,我对最后的每条车道都不感兴趣,而只对ID和欣赏感兴趣。如何修改我where的以在每个 ID 上完成?在条件中添加 ID 也不是选项。我尝试切换orfor and,但它没有返回任何值。我怎么能这样做?

4

1 回答 1

1

This should do the trick:

SELECT ID
FROM table
WHERE DRINK IN ('coffee','tea') -- or whatever else filter you want.
group by ID
HAVING MIN(appreciation) > 0

What it does is: It looks for the minimum appreciation and see to it that that is bigger than 0 for all lines in the group. And the group is the ID, as defined in the group by clause.

as you can see i'm using the having clause, because you can't have aggregate functions in the where section.

Of course you can join other tables into the query as you like. Just be carefull not to add some unwanted filter by joining, which might reduce your dataset in this query.

于 2013-07-04T15:53:32.350 回答