选择一行基于两列,一列带有ID,另一列带有列中的特定值

时间:2013-12-02 10:37:16

标签: sql sql-server sql-server-2008

我想根据特定列值和SQL

中的唯一id列选择行

表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 

我想将下表作为结果

    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,其中列“状态”仅选择了“新建”和“活动”

2 个答案:

答案 0 :(得分:5)

试试这个:

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只有两个状态newJOIN,而不再是| 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 | 使用原始表来获取列的结果。

这会给你:

{{1}}

答案 1 :(得分:0)

试试这个...

SELECT * FROM TABLENAME WHERE Acc_id IN 
(SELECT Acc_id FROM TABLENAME WHERE status IN ('Active','New') 
GROUP BY Acc_id Having COUNT(Acc_id)>1) AND status IN ('Active','New')