【问题标题】:Select a row based on two columns one with ID and another one with specific values in a column根据两列选择一行,一列具有 ID,另一列具有特定值
【发布时间】:2013-12-02 10:37:16
【问题描述】:

我想根据特定列值和 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”列和“状态”列的相同 ID 仅选择了“新建”和“活动”

【问题讨论】:

  • 向我们展示您尝试过的 SQL。
  • 另一个Acc_id 会发生什么,比如101 也是Active
  • 它们不应该被选中,只有 Acc_id 和 Active 和 New 作为它的状态应该被选中。

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


【解决方案1】:

试试这个:

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) = 2WHERE status IN('Active', 'New')会保证选中的Acc_id只有activenew两种状态,没有更多,然后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 |

【讨论】:

  • +1。您的查询是我的目标,但还没有完全实现。 :)
  • @FilipeSilva - 抱歉更快了 :)
  • @MahmoudGamal 我想在结果下添加一行。该行应包含一个新的“现有”状态,并且该值将是(状态“活动的值”-状态“新的值”)的结果,另一个应该保持不变。 eg:从上面介绍的第三行结果应该是这样 | 202 |净 |现有| -1 |
【解决方案2】:

试试这个...

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')

【讨论】:

  • 状态可能只有ActiveNewcount > 1
猜你喜欢
  • 2013-11-09
  • 2013-01-02
  • 1970-01-01
  • 2018-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多