0

I have following tables:

TABLE ITEMS Contains

ITEM_ID ITEM
-------------------
1       Food
2       Medical
3       Shopping
4       Others

TABLE EXPENSE_DURATION Contains

E_ID    NAME    FROM_DATE               TO_DATE
----------------------------------------------------------------
1   FEB_2012    1-Feb-2013 12:00:00 AM  28-Feb-2013 12:00:00 AM
2   MAR_2012    1-Mar-2013 12:00:00 AM  31-Mar-2013 12:00:00 AM

TABLE AMOUNT_FOR_EXPENSE Contains

AFE_ID  E_ID    ITEM_LIST   AMOUNT
------------------------------------
1       1       1,2,3,4     5000
2       2       1,2,3,4     6000

TABLE EXPENSE Contains

EXPENSE_ID  E_ID    ITEM_ID     DATE                    AMOUNT
---------------------------------------------------------------------
1          1        1           1-Feb-2013 12:00:00 AM  250
2          1        2           1-Feb-2013 12:00:00 AM  450
3          1        3           1-Feb-2013 12:00:00 AM  300
4          1        4           1-Feb-2013 12:00:00 AM  100
5          1        1           2-Feb-2013 12:00:00 AM  4500
6          1        2           2-Feb-2013 12:00:00 AM  3500
7          1        3           2-Feb-2013 12:00:00 AM  2000
8          1        4           2-Feb-2013 12:00:00 AM  1500

Now I want to make one stored Procedure that gives me expense_summary. I am passing Just E_ID as parameter to this stored procedure.

As a result I need one table contains respective summary.

Example: E_ID=1

Result:

TOTAL_OUT   TOTAL_IN    SUMMARY (IN-OUT)
12600       5000        -7600

I know only

SELECT SUM(AMOUNT) FROM EXPENSE WHERE E_ID=1

Result > 12600

And

SELECT AMOUNT FROM AMOUNT_FOR_EXPENSE WHERE E_ID=1

Result > 5000

I Know this two separate queries but I don’t know how to merge them and how to perform subtraction in select query with joins.

Please help to make select query / stored procedure so that I can generate result as I need.

4

2 に答える 2

4

次のクエリを使用して結果を取得できます。

select e.e_id, 
  e.Total_out, 
  a.amount Total_in,
  (e.Total_out - a.amount) * -1 Summary
from
(
  select sum(amount) Total_out,
    e_id
  from expense
  group by e_id
) e
left join AMOUNT_FOR_EXPENSE a
  on e.e_id = a.e_id
where e.e_id = 1

デモで SQL Fiddle を参照してください

于 2013-03-03T13:05:15.270 に答える
-2

これを試して

   SELECT SUM(AMOUNT),AMOUNT FROM EXPENSE ,AMOUNT_FOR_EXPENSE  WHERE E_ID=1
于 2013-03-03T12:18:41.983 に答える