我实际上发现了一些我可以解决的问题“需要帮助sql查询”。但如果能得到我具体问题的答案,我将不胜感激。
我有2个表,一个是TRANSACTIONS
,一个是EXPENSES
。
TRANSACTION:
transaction_id
emp_id
sales_date
total_sales
并且
EXPENSES:
expenses_id
emp_id
expense_date
expenses1
expenses2
total_expenses
我想将所有TRANSACTION.transaction_amount AS sales_sum WHERE TRANSACTION.sales_date = @sales_date and TRANSACTION.emp_id = @emp_id
.....总和,然后减去EXPENSES.total_expenses as expenses_deducted_sales WHERE EXPENSES.emp_id = TRANSACTION.emp_id AND TRANSACTION.sales_date = EXPENSES.expense_date
请帮助..谢谢
实施例
transaction_id emp_id sales_date total_sales
1 101 11/11/2012 300
2 101 11/11/2012 400
3 101 11/11/2012 300
expenses_id emp_id expenses_date expenses1 expenses2 total_expenses
1 101 11/11/2012 100 100 200
2 102 12/12/2012 50 50 100
3 103 10/12/2012 200 200 400
expenses_deducted_sales =(300 + 400 + 300) - 200
我已经尝试过AHiggins给出的代码并提出了这些代码:
选择 CashTransactionsTbl.emp_id, CashTransactionsTbl.trans_date, CashTransactionsTbl.total_amt - ISNULL(ExpensesTbl.total_expenses,0)AS expenses_deducted_sales 从 ( 选择 EMP_ID, TRANS_DATE, SUM(total_amt)AS sales_sum 来自CashTransactionsTbl GROUP BY emp_id,trans_date )tr LEFT JOIN ExpensesTbl ON tr.emp_id = ExpensesTbl.emp_id AND tr.trans_date = ExpensesTbl.trans_date 哪里 tr.trans_date = 2014-07-10
但是我没有这个错误说:
“操作数类型冲突:日期与int”
不兼容请帮忙!
答案 0 :(得分:0)
您需要两个派生表:一个包含每个员工的交易金额,一个包含每个员工的费用金额。全外连接以获取所有记录。
select
coalesce(t.emp_id, e.emp_id) as emp_id,
coalesce(t.sum_sales, 0) as sum_sales,
coalesce(e.sum_expenses, 0) as sum_expenses,
coalesce(t.sum_sales, 0) - coalesce(e.sum_expenses, 0) as expenses_deducted_sales
from
(
select emp_id, sum(total_sales) as sum_sales
from transaction
group by emp_id
) t
full outer join
(
select emp_id, sum(total_expenses) as sum_expenses
from expense
group by emp_id
) e on e.emp_id = t.emp_id;
答案 1 :(得分:0)
您需要先从交易中获取汇总数据,然后再将其与费用中的数据进行匹配,如下所示:
SELECT
tr.Emp_ID,
tr.Sales_Date,
tr.Sales_Sum - ISNULL(Expenses.Total_Expenses,0) AS Expenses_Deducted_Sales
FROM
(
SELECT
Emp_ID,
Sales_Date,
SUM(Total_Sales) Sales_Sum
FROM Transactions
) tr
LEFT JOIN
Expenses ON
tr.Emp_ID = Expenses.Emp_ID AND
tr.Sales_Date = Expenses.Expenses_Date
WHERE
tr.Sales_Date = @sales_date -- this could also go under the 'FROM Transactions' statement
答案 2 :(得分:0)
这非常粗糙,但这样的事情会起作用:
Select T_Sales.*,T_Sales.totalsales-totalexpesnses 'Expenses_deducted_sales'
from (
select t.emp_id,sales_date,SUM(totalsales) 'totalsales'
from #transaction t
group by t.emp_id,sales_date
) T_Sales
left join #expenses e
on T_Sales.emp_id = e.emp_id
and T_Sales.sales_date = e.expenses_date
where sales_date = @sales_date
PS。为拼写道歉 - 快速工作。