我正在尝试在多货币设置中执行SUM()。以下将说明我面临的问题: -
Customer
-------------------------
Id | Name
1 | Mr. A
2 | Mr. B
3 | Mr. C
4 | Mr. D
-------------------------
Item
-------------------------
Id | Name | Cost | Currency
1 | Item 1 | 5 | USD
2 | Item 2 | 2 | EUR
3 | Item 3 | 10 | GBP
4 | Item 4 | 5 | GBP
5 | Item 5 | 50 | AUD
6 | Item 6 | 20 | USD
7 | Item 3 | 10 | EUR
-------------------------
Order
-------------------------
User_Id | Product_Id
1 | 1
2 | 1
1 | 2
3 | 3
1 | 5
1 | 7
1 | 5
2 | 6
3 | 4
4 | 2
-------------------------
现在,我希望SELECT查询的输出列出客户名称和购买产品的总价值: -
Customer Name | Amount
Mr. A | Multiple-currencies
Mr. B | 25 USD
Mr. C | 15 GBP
Mr. D | 2 EUR
所以基本上,我正在寻找一种方法来在同一个客户下添加多个产品的成本,如果它们都具有相同的货币,则只需显示多种货币'。运行以下查询无济于事: -
SELECT Customer.Name, SUM(Item.Amount) FROM Customer
INNER JOIN Order ON Order.User_Id = Customer.Id
INNER JOIN Item ON Item.Id = Order.Product_Id
GROUP BY Customer.Name
我的查询应该是什么?我正在使用 Sqlite
答案 0 :(得分:0)
我建议使用两个输出列,一个用于货币,另一个用于金额:
SELECT c.Name,
(case when max(currency) = min(currency) then sum(amount)
end) as amount,
(case when max(currency) = min(currency) then max(currency)
else 'Multiple Currencies'
end) as currency
FROM Customer c INNER JOIN
Order o
ON o.User_Id = c.Id INNER JOIN
Item
ON i.Id = o.Product_Id
GROUP BY c.Name
如果需要,可以将这些连接到单个字符串列中。我更喜欢将这些信息放在两个不同的栏目中。
以上是标准SQL。
答案 1 :(得分:0)
我认为你的查询应该是这样的
SELECT
Data.Name AS [Customer Name],
CASE WHEN Data.Count > 1 THEN "Multiple-currencies" ELSE CAST(Data.Amount AS NVARCHAR) END AS Amount
FROM
(SELECT
Customer.Name,
COUNT(Item.Currency) AS Count,
SUM(Item.Amount) AS Amount
FROM
Customer
INNER JOIN Order ON Order.User_Id = Customer.Id
INNER JOIN Item ON Item.Id = Order.Product_Id
GROUP BY
Customer.Name) AS Data
获取货币计数的子查询,然后在主查询中询问它们以显示总数或文本“多种货币”。
很抱歉,如果有任何错误或错误,但我没有数据库服务器来测试它
希望这有帮助。
答案 2 :(得分:0)
IMO我首先要标准化变量名称。为什么在订单表中的客户表USER_ID中调用ID?只是一个小小的烦恼。无论如何,您应该学习如何构建查询。
首先将customer表加入订单表,然后将结果加入item表。第一个连接在CUSTOMER_ID上,第二个连接在PRODUCT_ID上。一旦你有工作使用SUM和GROUP BY
答案 3 :(得分:0)
好的,我设法通过这种方式解决了问题: -
SELECT innerQuery.Name AS Name, (CASE WHEN innerQuery.Currencies=1 THEN (innerQuery.Amount || innerQuery.Currency) ELSE 'Mutliple-Currencies' END) AS Amount, FROM
(SELECT Customer.Name, SUM(Item.Amount), COUNT(DISTINCT Item.Currency) AS Currencies, Item.Currency AS Currency FROM Customer
INNER JOIN Order ON Order.User_Id = Customer.Id
INNER JOIN Item ON Item.Id = Order.Product_Id
GROUP BY Customer.Name)innerQuery