Sql Query帮助需要

时间:2011-12-15 14:05:34

标签: mysql sql oracle

查询1:

select accnt_no,sum(no_shares)Buy from psdr_cds
where accnt_no between 1 and 9999
and trans_dt between '1-jan-2000' and '1-dec-2011'
and comp_cd=101 group by accnt_no;

查询2:

select accnt_no,sum(no_shares)Sell from swr_cds
where accnt_no between 1 and 9999
and trans_dt between '1-jan-2000' and '1-dec-2011'
and comp_cd=101 group by accnt_no;

最终查询:

select i.accnt_no,i.ac_name1 from inv_profile i
where i.accnt_no in(select accnt_no from psdr_cds
where accnt_no between 1 and 9999
and trans_dt between '1-jan-2000' and '1-dec-2011'
and comp_cd=101
union
select accnt_no from swr_cds
where accnt_no between 1 and 9999
and trans_dt between '1-jan-2000' and '1-dec-2011'
and comp_cd=101)

使用query1,query2和final查询我生成了结果 -

accnt_no    ac_name1         Buy         Sell        Balance
12          Prasun           300          150         150
34          Abc              300          0           300

现在我想使用单个查询而不是这三个查询返回相同的结果。 任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:4)

没有你的数据或架构,我无法真正测试它,但我认为这可能会做到:

SELECT i.accnt_no,i.ac_name1
FROM inv_profile i
LEFT JOIN psdr_cds p ON p.accnt_no = i.accnt_no
LEFT JOIN swr_cds s ON s.accnt_no = i.accnt_no
WHERE i.accnt_no between 1 and 9999
AND ((p.trans_dt between '1-jan-2000' AND '1-dec-2011' AND p.comp_cd=101)
OR (s.trans_dt between '1-jan-2000' AND '1-dec-2011' AND s.comp_cd=101))

否则,我没有看到基于UNION的子查询有任何明显错误。虽然不是最优的,但最终可能是最好的方式。