[英]Sql Query help need
查詢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;
QUERY2:
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的子查詢有任何明顯錯誤。 雖然不是最佳的,但最終可能是最好的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.