sql server query:如何选择超过1个订单的客户

时间:2013-07-19 05:50:53

标签: sql sql-server

我是一名sql server新手并试图选择所有拥有1个以上订单的客户。该表如下所示:

CREATE TABLE [dbo].[orders](
    [customerid] [int] NULL,
    [orderid] [int] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[orders] ([customerid], [orderid]) VALUES (1, 2)
INSERT [dbo].[orders] ([customerid], [orderid]) VALUES (1, 3)
INSERT [dbo].[orders] ([customerid], [orderid]) VALUES (2, 4)
INSERT [dbo].[orders] ([customerid], [orderid]) VALUES (2, 5)
INSERT [dbo].[orders] ([customerid], [orderid]) VALUES (3, 1)

2 个答案:

答案 0 :(得分:9)

select  customerid
,       count(*) as order_count
from    orders
group by
        customerid
having  count(*) > 1

答案 1 :(得分:1)

因为您可能在某个时候需要客户数据,您也可以尝试:

select *
from customers
where exists (
    select count(*)
    from    orders
    where customers.id = customerid
    group by customerid
    having  count(*) > 1
)