0

我有 2 个表。一个是 OrderMaster,第二个是 OrderDetails。两者都通过 OrderId 连接

订单表字段:OrderId(Primary Key),Total,OrderDate

OrderDetail 字段:OrderDetailId,ItemId,SupplierId,Amount,OrderId (ForiegnKey)

一个订单可以有多个来自不同供应商的订单详细记录

现在我想获得仅具有特定供应商 ID 值(例如:4)和计数(不同供应商 ID)=2 的订单。所有具有此供应商 ID 的订单不应包含在结果集中,因为其中一些可能有其他供应商也。预期输出是 OrderId, Sum*Amount 对于那些属于特定供应商的记录(订单中只有这个供应商)

编辑:我认为 Count(supplierId)=1 应该是查询的一部分。

4

3 回答 3

1

尝试这样的事情:

select OrderId, Sum(Amount) 
from OrderDetail 
where SupplierId = 4 
group by OrderId
于 2009-12-13T10:46:17.867 回答
1

Here's one way to select orders with only one particular supplier. The where clause looks for details for that supplier, and filters out orders with mixed suppliers. The Total is then calculated for each detail row.

select     od.OrderId
,          sum(od.Sum * od.Amount) as Total
from       OrderDetails od
where      od.SupplierId = 4
and        not exists (
           select   *
           from     OrderDetails od2
           where    od2.OrderId = od.OrderId
           and      od2.SupplierId <> od.SupplierId
           )
group by   od.OrderId

I'm not sure the sum is correct; here it's multiplying the Sum column with the Amount column. If you just need amount, you could write it like:

,          sum(od.Amount) as Total

Joining on OrderMaster is not required, since we can grab the OrderId from the details table.

于 2009-12-13T10:48:18.883 回答
0

You can try something like this.

DECLARE @Supl INT

SELECT @Supl = 4

SELECT  om.OrderID,
        SUM(Amount) TotalForSupplier
FROm    OrderMaster om INNER JOIN
        OrderDetails od ON om.OrderID = od.OrderID
WHERE   od.SupplierId = @Supl
GROUP BY om.OrderID

This will get you the totals for a given supplier accross orders.

This should probable include a price field,

SUM(Amount * Price)

If you wish to only have the OrderID and Total you can exclude the inner join

SELECT  od.OrderID,
    SUM(od.Amount) TotalForSupplier
FROm    OrderDetails od
WHERE   od.SupplierId = @Supl
GROUP BY od.OrderID
于 2009-12-13T10:47:53.300 回答