[英]SQL to find the names of all columns in a table where the SUM of the column is greater than zero
[英]SQL: Where result of 2 SUM() is greater than 0 in another table
這是場景:
---------------
|Table A |
|---------------|
|tba_id tba_name|
|1 Item A |
|2 Item B |
---------------
-------------------------------------
|Table B |
|-------------------------------------|
|tbb_id tbb_tbaid tbb_qtyIn tbb_qtyOut|
|1 1 5 0 |
|2 2 4 0 |
|3 2 7 0 |
|4 1 0 5 |
-------------------------------------
表 A 是我存儲項目詳細信息的地方。 表 B 是我存儲進出表 A 的數量的地方。我想通過單個 SQL 查詢行檢索表 B 中數量大於 0 的所有表 A。 這意味着它將類似於:qtyIn 的總和 - qtyOut 的總和 > 0。
使用聚合
select a.tba_name
from tabla a join tableb b on a.tba_id=b.tbb_tbaid
group by a.tba_name
having (sum(tbb_qtyIn)-sum(tbb_qtyOut))>0
嘗試這個:
select a.tba_name from TableA a where exists(
select * from TableB b where a.tba_id=b.tbb_tbaid group by b.tbb_tbaid having
(sum(tbb_qtyIn)-sum(tbb_qtyOut))>0);
您可以使用單個sum()
:
select a.tba_id, a.tba_nam
from a inner join
b
on a.tba_id = b.tbaid
group by a.tba_id, a.tba_nam
having sum(b.tbb_qtyIn - b.tbb_qtyOut) > 0
我傾向於將其寫為:
select a.tba_name
from TableA a
where (select sum(b.tbb_qtyIn) - sum(b.tbb_qtyOut)
from TableB b
where a.tba_id = b.tbb_tbaid
) > 0;
計算凈額的標量子查詢似乎是最直接的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.