6

我是一个 sql server 新手,并试图选择所有具有超过 1 个 orderid 的客户。该表如下所示:

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)
4

2 回答 2

14
select  customerid
,       count(*) as order_count
from    orders
group by
        customerid
having  count(*) > 1
于 2013-07-19T05:52:10.923 回答
2

由于您可能在某些时候需要客户数据,因此您也可以尝试:

select *
from customers
where exists (
    select count(*)
    from    orders
    where customers.id = customerid
    group by customerid
    having  count(*) > 1
)
于 2021-01-28T09:34:09.213 回答