繁体   English   中英

我正在尝试从两个表SQL Oracle 10g中检索数据

[英]I am trying to retrieive data from two tables SQL Oracle 10g

我有两个表tbl_inc t和tbl_expn。 两个表的所有字段都相同,除了它的主键之外,我想获取金额以显示一年中一个月的图表,并且每天都有sum(t.amount)和sum(d.amount)。 我一天有多笔款项。 以下代码不会将每天的金额相加

select extract(day from t.date_id) as tday,
extract(month from t.date_id) as mon,
extract(year from t.date_id) as yr,
t.amount as incamt,
d.amount as expamt 
from tbl_inc t,tbl_expn d 
where t.user_id=d.user_id and 
t.user_id='222' and 
extract(month from t.date_id)='04' and 
extract(month from d.date_id)='04' and 
extract(year from t.date_id)='2015' and 
extract(year from d.date_id)='2015' and 
extract(day from t.date_id)=extract(day from d.date_id) 
order by t.date_id

此代码的结果是这样

TDAY    MON YR      INCAMT  EXPAMT
29      4   2015    50      600
29      4   2015    100     200
29      4   2015    50      200
29      4   2015    100     600
30      4   2015    70      700
30      4   2015    30      500
30      4   2015    70      700
30      4   2015    30      500

我希望输出为

TDAY    MON YR      INCAMT  EXPAMT
29      4   2015    150     800
30      4   2015    100     1200

请帮忙...

看起来您需要SUMGROUP BY尝试一下:

select 
    extract(day from t.date_id) as tday,
    extract(month from t.date_id) as mon,
    extract(year from t.date_id) as yr,
    SUM(t.amount) as incamt,
    SUM(d.amount) as expamt 
from tbl_inc t,tbl_expn d 
where t.user_id=d.user_id and 
    t.user_id='222' and 
    extract(month from t.date_id)='04' and 
    extract(month from d.date_id)='04' and 
    extract(year from t.date_id)='2015' and 
    extract(year from d.date_id)='2015' and 
    extract(day from t.date_id)=extract(day from d.date_id) 
GROUP BY extract(day from t.date_id), extract(month from t.date_id), extract(year from t.date_id)
order by t.date_id

您还需要将from tbl_inc t,tbl_expn d更改为适当的JOIN以避免重复。

如果您的date_id没有时间部分,则可以删除trunc 如果时间段在那, trunc将丢弃该时间段。

您只需选择一个月,就可以对分组的日期和年份和月份进行无用的分组和选择,因为您已经知道它们。

select extract(day from t.date_id) as tday
     , ta as incamt
     , da as expamt 
     , t.*, d.*

from ( select trunc(date_id) date_id, user_id, sum(amount) ta from t group by trunc(date_id), user_id ) t
   , ( select trunc(date_id) date_id, user_id, sum(amount) da from d group by trunc(date_id), user_id ) d
where t.user_id = d.user_id 
  and t.date_id = d.date_id

  and t.user_id=1
  and extract(month from t.date_id)='04'
  and extract(year  from t.date_id)='2015'

order by extract(day from t.date_id)

您没有写任何关于行数的信息,但是在两个表上都需要一个索引。 我建议在其中一个上使用user_id, trunc(date_id) user_id, extract(month from date_id), extract(year from date_id)user_id, extract(month from date_id), extract(year from date_id)user_id, extract(month from date_id), extract(year from date_id) user_id, trunc(date_id)

参见http://sqlfiddle.com/#!4/83efc/6

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM