假设我有表orders
id name
1 order1
2 order2
3 order3
和子表items
id parent amount price
1 1 1 10
2 1 3 20
3 2 2 5
4 2 5 1
我想创建带有添加列value
的订单的查询。它应该用所有相关项目计算订单
id name value
1 order1 70
2 order2 15
3 order3 0
这是否可以使用TSQL
答案 0 :(得分:2)
GROUP BY
和SUM
会这样做,需要使用left join
和isnull
,因为您没有所有订单的商品。
SELECT o.id, o.name, isnull(sum(i.amount*i.price),0) as value
FROM orders o
left join items i
on o.id = i.parent
group by o.id, o.name
答案 1 :(得分:0)
我认为你正在寻找类似的东西
SELECT o.name, i.Value FROM orders o WITH (NOLOCK)
LEFT JOIN (SELECT parent, SUM(price) AS Value FROM items WITH (NOLOCK) GROUP BY parent) i
ON o.id = i.parent
...似乎RADAR打败了我的答案。 编辑:错过了ON线。