为了概括,我有一个与以下结构类似的数据库:
CustomerDatabase
ProductID | ProductName | CustomerID | Gender |
008100 | Laptop | 1 | Male |
008101 | Desktop | 2 | Female |
008100 | Laptop | 3 | Female |
008102 | Printer | 4 | Male |
008101 | Desktop | 5 | Female |
我可以运行什么声明来显示仅由特定性别而非另一种性别购买的产品ID?
示例结果如下:
ProductID | Gender | CustomerID|
008101 | Female | 2 |
008101 | Female | 5 |
因为产品“008101”仅由女性而非男性购买。
提前致谢。
答案 0 :(得分:1)
另一种方法是对Female
大于Female
的事实使用单select t.productid
from YourTable t
group by t.productid
having MAX(t.gender) = 'Female'
个中继,因此如果最大值为{{1}},那么它是唯一的之一。
{{1}}
答案 1 :(得分:0)
您可以使用聚合和having
:
select productid
from t
group by productid
having min(gender) = max(gender) and min(gender) = 'F';
您可以使用join
,in
或exists
获取原始表格中的行:
select t.*
from t join
(select productid
from t
group by productid
having min(gender) = max(gender) and min(gender) = 'F'
) tf
on t.productid = tf.productid;
答案 2 :(得分:0)
要仅让productID
女性订购,您可以
select productid
from your_table
group by productid
having sum(gender = 'Male') = 0
并且只能获得productID
仅订购的单一性别
select productid
from your_table
group by productid
having count(distinct gender) = 1