各国之间的贸易平衡 - Northwind数据库

时间:2018-04-25 10:57:25

标签: sql sql-server northwind

我有很多任务要做,使用旧的Northwind数据库,我需要为每个国家创建一个交易余额。这意味着,我需要算一下,每个国家每个国家卖多少钱,买多少钱以及余额是多少。 我有一个表Countries,其中列为“CountryID, CountryName, ContinentID”。 如果国家/地区的原始名称不是CountryID,而是Suppliers

,我更愿意这样做

我的表格SupplierID包含CountryId列,匹配CustomersCustomerID表,CountryId.SELECT c.CountryID, SUM(CONVERT(money, (od.UnitPrice * od.Quantity) * (1 - od.Discount) / 100) * 100) AS ProductSales From Countries c LEFT OUTER JOIN Suppliers s ON c.CountryID = s.CountryID JOIN Customers cu ON c.CountryID = cu.CountryID JOIN Products p ON s.SupplierID = p.SupplierID JOIN Orders o ON cu.CustomerID = o.CustomerID JOIN [Order Details] od ON o.OrderID = od.OrderID GROUP BY c.CountryID

也是如此

到目前为止,我有这个:

9   2072561.58
6   65322.04
7   56430.15
4   106925.77
19  412799.24
13  17205.45
5   200785.20
16  35966.40
17  272475.70
11  78850.80
20  2947015.56
8   406791.55

结果:

alert()

我不认为它给了我任何接近我需要的东西,可能它只是所有销售产品的价值。我坚持这个任务,我提供你需要的任何信息。

1 个答案:

答案 0 :(得分:1)

它将如下所示(抱歉,我的本地方框中没有安装此数据库)。可能会有所帮助 -

select
    fc.Countryname as FromCountryName,
    tc.Countryname as ToCountryName,
    SUM(CONVERT(money, (od.UnitPrice * od.Quantity) * (1 - od.Discount) / 100) * 100)
from Suppliers as s
inner join Countries as fc on fc.id = s.countryid
inner join Products as p on p.supplierid = s.id
inner join [Order Details] as od on od.productid = p.id
inner join Orders as o on o.id = od.OrderId
inner join Customers as cu on cu.id = o.customerId
inner join Countries as tc on tc.id = cu.countryid
group by fc.Countryname, tc.Countryname

我们Group ByFromCountry的数据为ToCountry

对于第二个要求,如下面的评论(可能低于查询在性能方面效率不高) -

select
    max(fc.name) as CountryA,
    min(tc.name) as CountryB,
    BalanceAB = sum(case when fc.name > tc.name then (CONVERT(money, (od.UnitPrice * od.Quantity) * (1 - od.Discount) / 100) * 100) end),
    BalanceBA = sum(case when fc.name < tc.name then (CONVERT(money, (od.UnitPrice * od.Quantity) * (1 - od.Discount) / 100) * 100) end),
    SUM((case when fc.name < tc.name then -1 else 1 end) * CONVERT(money, (od.UnitPrice * od.Quantity) * (1 - od.Discount) / 100) * 100) as [Total(A - B)]
from @Supplier as s
inner join @Country as fc on fc.id = s.countryid
inner join @Product as p on p.supplierid = s.id
inner join @OrderDetail as od on od.productid = p.id
inner join @Order as o on o.id = od.OrderId
inner join @Customer as cu on cu.id = o.customerId
inner join @Country as tc on tc.id = cu.countryid
group by (case when fc.name < tc.name then fc.name+' to '+tc.name else tc.name+' to '+fc.name end)

输出 -

CountryA    CountryB    BalanceAB   BalanceBA   Total(A - B)
US          UK          20.00       200.00      -180.00