查询 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 和最终查询我生成了结果-
accnt_no ac_name1 Buy Sell Balance 12 Prasun 300 150 150 34 Abc 300 0 300
现在我想使用单个查询而不是这三个查询返回相同的结果。 谁能帮我解决这个问题?
最佳答案
没有您的数据或架构,我无法真正测试它,但我认为这可能会做到:
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 的子查询有任何明显的错误。虽然不是最佳方式,但它最终可能是最好的方式。
关于mysql - SQL查询帮助需要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8521345/