表I如下
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
以下代码
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');
提供下表
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”列的相同ID,其中列“状态”仅选择了“新建”和“活动”
另外,我还想在结果下添加一行。该行应包含一个新的“状态”“现有”,而“值”将是(状态“活动的值” - 状态“新值”)的结果,另一个应该保持不变。
例如:从上面的结果
| ACC_ID | NAME | STATUS | VALUE |
|--------|------|-------- |-------|
| 202 | net | Active | 2 |
| 202 | net | New | 3 |
| 202 | net | Existing| -1 |
| 303 | com | Active | 1 |
| 303 | com | New | 4 |
| 303 | com | Existing| -3 |
| 505 | gov | New | 2 |
| 505 | gov | Active | 3 |
| 505 | gov | Existing| 1 |
答案 0 :(得分:2)
您不需要当前查询的复杂性
SELECT active.acc_id,
active.acc_name,
'Existing',
active.value - new.value
INTO table1
FROM (SELECT * FROM table1 WHERE status = 'Active') active
JOIN (SELECT * FROM table1 WHERE status = 'New') new
ON active.acc_id = new.acc_id