SQL Server为group by添加相同id的价格,数量,但在group by中有另一个字段

时间:2018-02-01 14:33:10

标签: sql sql-server

我有这个代码及其临时表,因此您可以运行它。

create table #Category(
id int identity(1,1),
name varchar(50)
)

create table #Items(
id int identity(1,1),
name varchar(50),
category_id int,
price decimal(18,2)
)

create table #Order(
id int identity(1,1),
item_id int,
quantity int,
isactive tinyint
)

insert into #Category(name)
values('Breakfast'),('Lunch'),('Dinner')

insert into #Items(name,category_id,price)
values('Sandwich w/ Egg',1,20),('Sandwich w/ Hotdog',1,35),('Fried Chicken',2,50),('Salad',3,100)

insert into #Order(item_id,quantity,isactive)
values(1,2,1),(1,1,0),(2,4,1),(4,1,1)

drop table #Category
drop table #Items
drop table #Order

这将为您提供此输出

id          name        quantity         total
----------------------------------------------
1           Breakfast     3              60.00 
1           Breakfast     4              140.00 
2           Lunch         NULL           NULL
3           Dinner        1              100.00

我想和午餐和晚餐一起吃早餐

我的目标:

id          name        quantity         total
----------------------------------------------
1           Breakfast     7              200.00 
2           Lunch         NULL           NULL
3           Dinner        1              100.00

我的尝试:

select
C.id,
C.name,
sum(O.quantity) 'quantity',
sum(o.quantity) * I.price 'total'
from #Category C
left join #Items I
on I.category_id = C.id
left join #Order O
on O.item_id = I.id
group by C.id, C.name, I.price

这就是我得到的所有我需要你的帮助。

2 个答案:

答案 0 :(得分:4)

您想要总结数量和价格的乘积,您应该这样做:

select
C.id,
C.name,
sum(O.quantity) 'quantity',
sum(o.quantity * I.price) 'total'
from #Category C
left join #Items I
on I.category_id = C.id
left join #Order O
on O.item_id = I.id
group by C.id, C.name

答案 1 :(得分:1)

I.price

中取出GROUP BY