Group By Sum没有直接Id

时间:2017-01-25 01:13:41

标签: sql tsql

有两个表,Orders和OrderDetails,设置如此。

订单

 +--------------------+
 | ClientId | OrderId |
 +--------------------+
 |   Foo    |   1     |
 |   Foo    |   2     |
 |   Bar    |   3     |
 +--------------------+ 

订单明细

 +---------+-------+
 | OrderId | Sales |
 +---------+-------+
 |    1    |  10   |
 |    2    |  10   |
 |    3    |  10   |
 +---------+-------+

我需要一个没有任何Join的查询,返回以下内容

+----------+-------+
|          | Total |
| ClientId | Sales |
+----------+-------+
|   Foo    |  20   |
|   Bar    |  10   |
+----------+-------+

想法?

1 个答案:

答案 0 :(得分:0)

这是使用cte的另一种选择 但正如蒂姆所说,join应该是最好的解决方案

declare @order table (ClientID varchar(3), OrderId int)
declare @orderDetails table (OrderId int, Sales int)

insert into @order values ('Foo', 1), ('Foo', 2), ('Bar', 3)
insert into @orderDetails values (1, 10), (2, 10), (3, 10)

;with ctx as (
select o.ClientID,
        (select sum(Sales) from @orderDetails d where d.OrderId = o.OrderId) sales
from @order o
)
select ClientID, SUM(sales) TotalSales
from ctx
group by ClientID

-- With normal join
select o.ClientID, SUM(d.Sales) as TotalSales
from @order o
left join @orderDetails d on o.OrderId = d.OrderId
group by o.ClientID

如果您想要完全匹配,可以将left join更改为inner join