我有表像
PONO LINESNO status
1 10 X
1 20 X
1 30 y
2 10 X
2 20 X
2 30 X
在这里,在这个表中我们有对用不同的状态,为每个LINESNO
2 PO
2个独特PO数字1和2。我想编写一个查询只返回所有LINESNO
具有同等的地位e.g如果我在传递状态PO Where子句“Where Status='X'
”,那么它应该与PO 2,因为PO2
让所有LINESNO
与X
相同的状态只返回一行
<table>
<tr>
<td>
PO NO
</td>
<td>
LINENO
</td>
<td> Status</td>
</tr>
<tr>
<td> 1 </td>
<td> 10 </td>
<td> X</td>
</tr>
<tr>
<td> 1 </td>
<td> 20 </td>
<td> X</td>
</tr>
<tr>
<td> 1 </td>
<td> 30 </td>
<td> Y</td>
</tr>
<tr>
<td> 2 </td>
<td> 10 </td>
<td> X</td>
</tr>
<tr>
<td> 2 </td>
<td> 20 </td>
<td> X</td>
</tr>
<tr>
<td> 3 </td>
<td> 30 </td>
<td> X</td>
</tr>
</table>
我想这可能是工作:
架构(MySQL的V5.7)
create table pos (pono int, LINESNO int, status varchar(1));
insert into pos values (1, 10, 'x');
insert into pos values (1, 20, 'x');
insert into pos values (1, 30, 'y');
insert into pos values (2, 10, 'x');
insert into pos values (2, 20, 'x');
insert into pos values (2, 30, 'x');
insert into pos values (3, 20, 'x');
insert into pos values (3, 30, 'y');
insert into pos values (4, 30, 'x');
查询#1
Select a.pono, a.total_pono, b.total_status from
(select pono, count(*) as total_pono from pos group by pono) a,
(select pono, count(*) as total_status from pos where status = 'x' group by pono) b
where a.total_pono = b.total_status
and a.pono = b.pono;
| pono | total_pono | total_status |
| ---- | ---------- | ------------ |
| 2 | 3 | 3 |
| 4 | 1 | 1 |