Sql 如何使用相同的id进行分组?

Sql 如何使用相同的id进行分组?,sql,postgresql,Sql,Postgresql,我想要购买产品X、Y和Z的客户ID,来自以下模式: 销售(customerid、productName、rid) 我可以在十字路口: select customerid from sales where productName='X' INTERSECT select customerid from sales where productName='X' INTERSTECT select customerid from sales where productName='Z' 这是我能做

我想要购买产品X、Y和Z的客户ID,来自以下模式:

销售(customerid、productName、rid)

我可以在十字路口:

select customerid from sales where productName='X' 
INTERSECT 
select customerid from sales where productName='X' 
INTERSTECT
select customerid from sales where productName='Z'

这是我能做的最好的了吗?

不确定这在postrgesql中是否有效,但请尝试:

select customerid 
from sales 
where productName in ('X', 'Y', 'Z')
group by customerid
having count(distinct productName) = 3

不确定这是否适用于postrgesql,但请尝试:

select customerid 
from sales 
where productName in ('X', 'Y', 'Z')
group by customerid
having count(distinct productName) = 3

您还可以从sales中选择3次:

select s1.customerID
from sales s1, sales s2, sales s3
where s1.productName = 'X'
    and S2.productName = 'Y'
    and S3.productName = 'Z'
    and (S1.customerID = S2.customerID
         and s2.customerID = s3.customerID);
或者使用正确的连接语法重写(虽然可能不是100%…)


您还可以从sales中选择3次:

select s1.customerID
from sales s1, sales s2, sales s3
where s1.productName = 'X'
    and S2.productName = 'Y'
    and S3.productName = 'Z'
    and (S1.customerID = S2.customerID
         and s2.customerID = s3.customerID);
或者使用正确的连接语法重写(虽然可能不是100%…)


是的,成功了。我不知道in的用法。你还能怎么写呢?是否需要having count子句?中的
类似于
:这:
中的where productName IN('X','Y','Z')
也可以写成
中的where(productName='X'或productName='Y'或productName='Z')
(distinct…子句确保只返回购买了所有三种产品的客户。如果没有它,查询将返回购买了这三种产品中任何一种的所有客户。这是一个有效的替代方案。我很好奇哪一种性能更好。是的,这很有效。我不知道in的用法。你还能写什么您是否需要having count子句?
中的
类似于
:这:
where productName in('X','Y','Z')
也可以写成
where(productName='X'或productName='Y'或productName='Z')
。having count(distinct…子句确保只返回购买了所有三种产品的客户。如果没有它,查询将返回购买了这三种产品中任何一种的所有客户。这是一个有效的替代方案。我很好奇哪一种性能更好。您所说的(可能不是100%)是什么意思?我实际上没有尝试过,而且我已经好几年没有使用postgresql了,所以我不是100%我的语法完全正确,但是如果它有错误,你可能会修复它。你说的(可能不是100%)是什么意思?我实际上没有尝试过,而且我已经好几年没有使用postgresql了,所以我不是100%我完全正确地理解了语法,但是如果它有错误,你可能会修复它。