一个(稍微复杂)的SQL查询?

时间:2012-03-18 02:50:44

标签: sql ms-access select sum union

我有这个复杂的(对我而言)要求,并希望得到一个SQL查询。这是交易:

  • 这个表在Access文件中名为“Expenses”。
  • 该表包含“类别”,“金额”,“付款人”和“IsShare”等字段。
  • 类别可以是煤气,杂货,家居等......
  • 金额是费用的美元金额。
  • 付款人可以是我或我的兄弟(“我”或“兄弟”)。
  • IsShare可以是真的也可以是假的。基本上如果IsShare是真的,则费用分为两部分。否则,付款人会支付全部费用。

我需要一个SQL查询来计算特定类别的所有费用。它应该这样计算:

  • 我支付的所有非共享项目的100%(Payer ='Me'和IsShare = false),
  • 我支付的所有共享项目的50%(Payer ='Me'和IsShare = true),
  • 我哥哥支付的所有共享项目的50%(Payer ='Bro'和IsShare = true)。

查询应该返回所有这三个项的总和。

到目前为止,我有一个初步查询,但它返回不正确的结果。有人能为我纠正吗?

非常感谢。

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";

1 个答案:

答案 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