我有两个表,一个是Customer Detail,另一个是Order Detail。每次客户订购时,它都会将其存储在数据库中。如何查找客户订单以及订购和合并客户名称和订单的次数?
CUSTOMER DETAIL:
ID NAME AGE COUNTRY
1 AAA 22 US
2 BBB 26 UK
3 CCC 25 TN
ORDER DETAIL:
ID ITEMS PRICE QUANTITY
1 APPLE 5
1 ORANGE 6
1 MANGO 4
客户AAA有很多订单。
预期结果:
CUSTOMERDETAIL ORDERDETAIL
AAA (HOW MANY TIMES HE ORDER AND ORDER DETAILS)
答案 0 :(得分:2)
Create Table Customer (CustomerId int identity(1,1),Name varchar(20))
Create Table OrderDetail(OrderDetailId int identity(1,1), CustomerId int, Item varchar(20), Quantity int)
Insert into Customer values('AAA')
Insert into Customer values('BBB')
Insert into Customer values('CCC')
Insert into OrderDetail values(1,'Apple',10)
Insert into OrderDetail values(1,'Banana',10)
Insert into OrderDetail values(1,'Mango',10)
select y.total, x.Item,x.quantity from
(
select c.customerId as customerId, d.Item, d.quantity from customer c inner join orderdetail d
on c.customerId = d.customerId
)x
inner join
(
select customerid, COUNT(customerId)as total from orderdetail group by customerId
)y
on x.customerId = y.customerId
答案 1 :(得分:1)
假设你有这样的架构:
客户表(客户)
ID (Customer Id) int primary key
Name varchar(100)
订单表(订单)
ID (Order ID) int
cusotmer_id (reference id of customer table primary key-ID) int
quality int
price float
针对eash客户的第一个订单计数:
select count(o.customer_id) as total_order, c.* from customer c left join orders o on c.ID = o.customer_id
针对单个客户列出的订单:
c.ID = o.customer_id上的 select c.*, o.* from customer c
内连接顺序o,其中c.ID = 1
我希望这会对你有所帮助。
答案 2 :(得分:1)
以下查询给出了我的期望。
SELECT name,items,price FROM customerdetail INNER JOIN orderdetail ON customerdetail .sno = orderdetail .id WHERE id = 1;