sql server结果加倍和三倍

时间:2012-12-25 16:44:02

标签: sql-server vb.net

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

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)总是加倍。

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

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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;

答案 2 :(得分: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