我想根据特定的列值和SQL中的唯一id列选择行
我的表如下
Acc_id | Name | Status | value
----------------------------------------
101 | com | Active | 1
202 | net | Active | 2
202 | net | New | 3
303 | com | Active | 1
303 | com | New | 4
303 | com | Inactive | 2
404 | org | Active | 5
404 | org | Inactive | 6
505 | gov | New | 2
505 | gov | Active | 3
我希望得到下表
Acc_id | Name | Status | value
----------------------------------------
202 | net | Active | 2
202 | net | New | 3
303 | com | Active | 1
303 | com | New | 4
505 | gov | New | 2
505 | gov | Active | 3
如您在上方看到的,对于来自“ Acc_id”列和具有“ Status”列的相同ID,仅选择了“ New”和“ Active”
试试这个:
SELECT
t1.*
FROM table1 AS t1
INNER JOIN
(
SELECT Acc_id
FROM table1
WHERE status IN('Active', 'New')
GROUP BY Acc_id
HAVING COUNT(DISTINCT status) = 2
) AS t2 ON t1.Acc_id = t2.Acc_id
WHERE t1.status IN('Active', 'New');
在HAVING COUNT(DISTINCT status) = 2
与WHERE status IN('Active', 'New')
将确保所选择的Acc_id
只有两种状态active
,并new
没有更多的,则JOIN
与原来的表来获取列的结果。
这将为您提供:
| ACC_ID | NAME | STATUS | VALUE |
|--------|------|--------|-------|
| 202 | net | Active | 2 |
| 202 | net | New | 3 |
| 303 | com | Active | 1 |
| 303 | com | New | 4 |
| 505 | gov | New | 2 |
| 505 | gov | Active | 3 |
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句