1

特定のテーブルを作成したいのですが、結果の一部の数値が2倍または3倍になります。これが状況です:

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)が常に2倍になることです。

だからどんなアイデアも...

4

3 に答える 3

3

2 つのテーブル間の関係を指定する必要があるようです。

このようなものだと思います:

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 に答える