I have this complex (to me) requirement and would appreciate a SQL query for it. Here’s the deal:
- There’s this table named “Expenses” in an Access file.
- The table contains fields as “Category,” “Amount,” “Payer,” and “IsShare.”
- Category can be Gas, Groceries, Home, etc…
- Amount is the dollar amount for the expense.
- Payer can either be me or my brother (“Me” or “Bro”).
- IsShare can either be true or false. Basically if IsShare is true, then the expense is divided in two. Otherwise, the payer pays for it all.
I need a SQL query to calculate all my expenses for a particular Category. It should be calculated as such:
- 100% of all non-shared items that I’ve paid (Payer = ‘Me’ AND IsShare = false),
- 50% of all shared items that I’ve paid (Payer = ‘Me’ AND IsShare = true), and
- 50% of all shared items that my brother’s paid (Payer = ‘Bro’ AND IsShare = true).
The query should return the sum of all these three items.
So far I have a preliminary query, but it returns incorrect results. Could someone correct it for me?
Thank you very much.
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";
I don’t think the UNION is needed for what you are trying to do. This will pass over the data once and put the values in individual columns. You may need to cast or convert the 0.5 to a specific type, I didn’t have a chance to run this.
For MS ACCESS:
Add the three columns together: