Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql server query: how to select customers with more than 1 order

Tags:

sql

sql-server

I am a sql server newbie and trying to select all the customers which have more than 1 orderid. The table looks as follows:

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)
like image 662
user603007 Avatar asked Jul 19 '13 05:07

user603007


People also ask

How do I use more than one order in SQL?

Syntax: SELECT * FROM table_name ORDER BY column_name; For Multiple column order, add the name of the column by which you'd like to sort records first. The column that is entered at first place will get sorted first and likewise.

How do I select multiple items in SQL query?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

Can you have two ORDER BY statements in SQL?

SQL ORDER BY Multiple Columns However we can use multiple columns in ORDER BY clause. When multiple columns are used in ORDER BY, first the rows will be sorted based on the first column and then by the second column.

What is ORDER BY 3 in SQL?

Order by 3 DESC. In this query, column birthdate is at the 3rd position; therefore, we can use three in the Order by clause to sort results on this column data. Note: I would not recommend using column position in Order By clause. You should always use a column name in Order by clause.


2 Answers

select  customerid
,       count(*) as order_count
from    orders
group by
        customerid
having  count(*) > 1
like image 92
Andomar Avatar answered Nov 01 '22 23:11

Andomar


as you'll probably need customer data at some point, you could also try:

select *
from customers
where exists (
    select count(*)
    from    orders
    where customers.id = customerid
    group by customerid
    having  count(*) > 1
)
like image 3
smknstd Avatar answered Nov 02 '22 00:11

smknstd