Witam, mam mały problem z moim skryptem zapytań w SQL Server.
Korzystam z starej bazy Northwind, muszę napisać query, które wyrzuci mi całkowity bilans handlowy między wszystkimi państwami.
Na chwilę obecną mam coś takiego:
SELECT
MAX(ca.CountryName) as CountryA,
MIN(cb.CountryName) as CountryB,
SUM(case when ca.CountryName < cb.CountryName then (CONVERT(money, (od.UnitPrice * od.Quantity) * (1 - od.Discount) / 100) * 100) end) as Selling,
SUM(case when ca.CountryName > cb.CountryName then (CONVERT(money, (od.UnitPrice * od.Quantity) * (1 - od.Discount) / 100) * 100) end) as Buying,
SUM((case when ca.CountryName > cb.CountryName then -1 else 1 end) * CONVERT(money, (od.UnitPrice * od.Quantity) * (1 - od.Discount) / 100) * 100) as Balance
FROM Orders o
INNER JOIN [Order Details] od on o.OrderID=od.OrderID
INNER JOIN Products p on p.ProductID = od.ProductID
INNER JOIN Suppliers s on s.SupplierID = p.SupplierID
INNER JOIN Customers c on o.CustomerID = c.CustomerID
INNER JOIN Countries ca ON ca.CountryID = s.CountryID
INNER JOIN Countries cb ON cb.CountryID = c.CountryID
GROUP BY (case when ca.CountryName < cb.CountryName then ca.CountryName+' to '+cb.CountryName else cb.CountryName+' to '+ca.CountryName end)
ORDER BY CountryA, CountryB
Skrypt po części działa, ale jest kilka problemów.
Oparłem go na "(case when ca.CountryName < cb.CountryName then..."
Przez co wyrzuca mi niepoprawne wyniki.
Załączam diagram bazy danych (plus dodano dwie tabelki, Countries i Continents)..
Jak mam poprawić moje query by poprawnie sumowało mi transakcje między krajami i poprawnie je odejmowało?
Otrzymuję coś takiego:
France Austria NULL 29307.20 29307.20
France Belgium NULL 6246.00 6246.00
France Brazil 160.20 36818.45 36658.25
France Canada 9160.35 14927.66 5767.31
France Denmark 559.20 11817.10 11257.90
France Finland 2413.10 2779.85 366.75
France France NULL NULL 5855.50
France Ireland 6101.38 NULL -6101.38
France Mexico 5971.00 NULL -5971.00
France Poland 669.00 NULL -669.00
France Portugal 1213.80 NULL -1213.80
France Switzerland 3458.40 NULL -3458.40
France Venezuela 9150.76 NULL -9150.76
Germany Argentina NULL 864.20 864.20
Germany Austria NULL 18884.33 18884.33
Germany Belgium NULL 7457.08 7457.08
Germany Brazil 334.80 11689.97 11355.17
Germany Canada 14994.36 2277.15 -12717.21
Germany Denmark 1545.50 5702.79 4157.29
Germany Finland 5587.04 1374.70 -4212.34
Germany France 63311.24 12720.25 -50590.99
Germany Germany NULL NULL 37210.66
Germany Ireland 18475.28 NULL -18475.28
Germany Mexico 2688.87 NULL -2688.87
Germany Poland 232.50 NULL -232.50