sql 特定列的 columnValue > 0
sql having columnValue > 0 by a specific column
我找不到任何解决方案 table :
DocId | Item| Service | Qty
1 | 10 | Energie activa | 9.7140000000
1 | 18 | Tarif distributie JT | 9.7140000000
1 | 19 | Tarif transport TG | 9.7140000000
1 | 20 | Tarif transport TL | 9.7140000000
1 | 14 | Serviciu sistem | 9.7140000000
1 | 15 | Cogenerare | 9.7140000000
我需要 select * 来自 table 每个 DocId,其中 Item = 15(这没问题)。但是,必须有另一个条件,即 Qty > 0 其中 Item 为 18、19 或 20
select *
from table
where item = 15
和类似的东西:
having Qty > 0 where Item = 18 or Item = 19 or Item = 20
我不需要像下面这样的代码,因为我的整个查询中有很多内连接和数以千计的 DocId。
select *
from table
where item = 15 and (select qty from table where item = 18 and docId = 1) > 0
您可以使用 group by
和 having
获得满足两个条件的 docids:
select docid
from table t
group by docid
having sum(case when item = 15 then 1 else 0 end) > 0 and
sum(case when item in (18, 19, 20) and qty then 1 else 0 end) > 0;
您可以使用 in
、exists
或 join
获取原始行。
如果你只想要 item = 15
的行,你可以直接使用 exists
:
select t.*
from table t
where t.item = 15 and
exists (select 1
from t t2
where t2.docid = t.docid and
t2.item in (18, 19, 20) and
t2.qty > 0
);
您可以使用括号来组合条件...
select *
from table
where item = 15 or (item in (18,19,20) and qty>0)
我找不到任何解决方案 table :
DocId | Item| Service | Qty
1 | 10 | Energie activa | 9.7140000000
1 | 18 | Tarif distributie JT | 9.7140000000
1 | 19 | Tarif transport TG | 9.7140000000
1 | 20 | Tarif transport TL | 9.7140000000
1 | 14 | Serviciu sistem | 9.7140000000
1 | 15 | Cogenerare | 9.7140000000
我需要 select * 来自 table 每个 DocId,其中 Item = 15(这没问题)。但是,必须有另一个条件,即 Qty > 0 其中 Item 为 18、19 或 20
select *
from table
where item = 15
和类似的东西:
having Qty > 0 where Item = 18 or Item = 19 or Item = 20
我不需要像下面这样的代码,因为我的整个查询中有很多内连接和数以千计的 DocId。
select *
from table
where item = 15 and (select qty from table where item = 18 and docId = 1) > 0
您可以使用 group by
和 having
获得满足两个条件的 docids:
select docid
from table t
group by docid
having sum(case when item = 15 then 1 else 0 end) > 0 and
sum(case when item in (18, 19, 20) and qty then 1 else 0 end) > 0;
您可以使用 in
、exists
或 join
获取原始行。
如果你只想要 item = 15
的行,你可以直接使用 exists
:
select t.*
from table t
where t.item = 15 and
exists (select 1
from t t2
where t2.docid = t.docid and
t2.item in (18, 19, 20) and
t2.qty > 0
);
您可以使用括号来组合条件...
select *
from table
where item = 15 or (item in (18,19,20) and qty>0)