我有这个复杂的(对我而言)要求,并希望得到一个SQL查询。这是交易:
我需要一个SQL查询来计算特定类别的所有费用。它应该这样计算:
查询应该返回所有这三个项的总和。
到目前为止,我有一个初步查询,但它返回不正确的结果。有人能为我纠正吗?
非常感谢。
return @"SELECT Sum(Amount) AS TotalAmount " +
"FROM Expenses " +
"WHERE Category = 'Groceries' " +
"AND Payer = 'Me' " +
"AND Share = false " +
"GROUP BY Category " +
"UNION " +
"SELECT 0.5 * Sum(Amount) AS TotalAmount " +
"FROM Expenses " +
"WHERE Category = 'Groceries' " +
"AND Payer = 'Me' " +
"AND Share = true " +
"GROUP BY Category " +
"UNION " +
"SELECT 0.5 * Sum(Amount) AS TotalAmount " +
"FROM Expenses " +
"WHERE Category = 'Groceries' " +
"AND Payer = 'Bro' " +
"AND Share = true ";
"GROUP BY Category";
答案 0 :(得分:2)
我认为你想要做的事情不需要UNION。这将传递一次数据并将值放在各列中。您可能需要将0.5转换或转换为特定类型,我没有机会运行它。
SELECT
Category,
SUM(CASE WHEN Payer='me' AND NOT IsShare THEN Amount ELSE 0 END) as IPaid,
SUM(CASE WHEN Payer='me' AND IsShare THEN Amount * 0.5 ELSE 0 END) as SharedPay,
SUM(CASE WHEN Payer='bro' AND IsShare THEN Amount * 0.5 ELSE 0 END) as BrotherPay
FROM Eexpenses
WHERE Category = 'Groceries'
GROUP BY Category
对于MS ACCESS:
SELECT
Category,
SUM(IIF(Payer='me' AND NOT IsShare, Amount,0)) as IPaid,
SUM(IIF(Payer='me' AND IsShare, Amount * 0.5, 0)) as SharedPay,
SUM(IIF(Payer='bro' AND IsShare, Amount * 0.5, 0)) as BrotherPay
FROM Eexpenses
WHERE Category = 'Groceries'
GROUP BY Category
将三列一起添加:
SELECT Category, IPaid, SharedPay, BrotherPay, IPay + SharedPay + BotherPay as Total
FROM (
SELECT
Category,
SUM(IIF(Payer='me' AND NOT IsShare, Amount,0)) as IPaid,
SUM(IIF(Payer='me' AND IsShare, Amount * 0.5, 0)) as SharedPay,
SUM(IIF(Payer='bro' AND IsShare, Amount * 0.5, 0)) as BrotherPay
FROM Eexpenses
WHERE Category = 'Groceries'
GROUP BY Category
) as T1