mysql - SQL查询帮助需要

标签 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 和最终查询我生成了结果-

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/

相关文章:

php - 在链接到数据库行中 id 的 URL 上使用 $_get

java - android AppWidget : SMS query works on emulator, 但不在真实设备上

javascript - 如何使链接出现在文本框中,并让按钮将其保存在数据库中

sql - 如何插入表默认值

mysql - 在列中添加临时逗号而不更新任何表

c# - 如何在没有 oracle 客户端或 tnsname 的情况下连接到 ORACLE DB

sql比较带有一些空值的字段

java - 从 servlet 中的查询结果返回 XML

MySql为某个ip创建用户

php - PDO 两表连接