根据2列值选择不同的行

时间:2019-02-08 13:30:11

标签: distinct

我有类似

的表格
PONO    LINESNO   status
1        10        X
1        20        X
1        30        y 
2        10        X
2        20        X
2        30        X

在此表中,我们有2个唯一的PO编号1和2,每个LINESNO上都有2个PO,具有单独的状态。 我想编写一个查询以仅返回所有LINESNO具有相同状态的PO 例如,如果我在Where子句“ Where Status='X'”中传递了Status 那么它应该只返回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>

1 个答案:

答案 0 :(得分:0)

我认为这可行:

模式(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            |

View on DB Fiddle