1

我想创建一个特定的表,但一些数值在结果中增加了一倍或三倍。情况如下:

2 表:付款和费用

[Payments]: ID, studentID, Amount, DOP (a row in this table is a payment which a student pays it on DOP (date).
[Expenses]: ID, AmountPaid, TimeStamp (a row in this table is an expense bought such as papers or pens... on a specific date(timestamp)

我的查询是:

select
sum(purchases.amount) as 'Income From Students',
sum(Expenses.amountpaid) as 'Expenses',
sum(purchases.amount-expenses.amountpaid) as 'Net Profit',
datename(month,timestamp) as 'Month',
datepart(year,timestamp) as 'Year' 
from expenses,purchases 
group by datename(month,timestamp),datepart(year,timestamp)

如查询所示:我的表格应显示每个月和每年的付款、费用和净额的总和profit=payments - expenses

问题是,当得到结果时, sum(expenses.amountpaid) 总是加倍。

所以任何想法......

4

3 回答 3

3

听起来您需要指定两个表之间的关系。

像这样的东西,我假设:

select
sum(purchases.amount) as 'Income From Students',
sum(Expenses.amountpaid) as 'Expenses',
sum(purchases.amount-expenses.amountpaid) as 'Net Profit',
datename(month,timestamp) as 'Month',
datepart(year,timestamp) as 'Year' 
from expenses,purchases 
WHERE PURCHASES.DOP = EXPENSES.TIMESTAMP /*Add this*/
group by datename(month,timestamp),datepart(year,timestamp)
于 2012-12-25T17:15:50.027 回答
0
SELECT T.INCOME,T.EXPENSE,SUM(T.INCOME)-SUM(T.EXPENSE) AS PROFIT 
FROM (SELECT SUM(P.amount) AS Income, SUM(E.amountpaid) AS Expense 
FROM Payments P,Expenses E WHERE P.ID=E.ID  
GROUP BY datename(month, timestamp), datepart(year, timestamp)) AS T;
于 2012-12-25T17:21:19.123 回答
0

我解决了伙计们,经过4个小时的尝试,查询是:

select sum(P.Income) as 'Income from Payments',
sum(E.expense) as 'Expenses',
sum(P.Income)-sum(E.expense) as 'Net Profit',
DateName( month , DateAdd( month , IncomeMonth , 0 ) - 1 ) as 'Month'
from
(select sum(payments.amountpaid) as Income,
month(DOP) as IncomeMonth
from payments group by month(dop)) as P,
(select sum(expenses.amountpaid) as Expense,
month(timestamp) as ExpenseMonth
from expenses 
group by month(timestamp))
as E
where
E.Expensemonth=P.IncomeMonth
group by P.IncomeMonth
于 2012-12-27T23:07:21.157 回答