有没有办法检查几行中某个列值是否相同?
我需要检查客户是否在我的数据库中放置了多个订单。
如果我选择
SELECT * FROM orders WHERE email = 'customer@email.com'
这可能会产生
OrderID Product Amount email
50 Apples 1 customer@email.com
50 Oranges 1 customer@email.com
50 Bananas 1 customer@email.com
91 Apples 1 customer@email.com
所以我需要检查这些行中的OrderID是否相同。
但是怎么样?
答案 0 :(得分:1)
使用count()函数和group by子句来警告订单ID包含的记录数:
select email, orderid, count(*) as number_orders_per_orderid
from orders
where email = 'customer@email.com'
group by email, orderid
或者,如果您想计算用户订单的数量,请使用count(distinct ...)和group by:
select email, count(distinct orderid) as number_of_orders
from orders
where email = 'customer@email.com'
group by email
答案 1 :(得分:1)
您可以使用分组和
select id, count(*) from orders group by id
WHERE email = 'customer@email.com'
having count(*) > 1
答案 2 :(得分:0)
你可以得到一个"只有一个"如果客户有一个ORDERID
如果客户使用CASE ... WHEN
具有多个ORDERID
这是一个例子
SELECT email,COUNT(*) as number_order ,
(CASE WHEN count(*)=1 THEN "Just one" WHEN count(*)>1 THEN "More than one" END) AS number_order_status
FROM orders GROUP BY email