【问题标题】:Join tables with same keys, second table has multiple values for key and rows of second table must have same column value连接具有相同键的表,第二个表有多个键值,第二个表的行必须具有相同的列值
【发布时间】:2020-03-15 20:57:59
【问题描述】:

我有两个具有共享密钥的表,我正在尝试将它们加入以根据少数条件过滤数据

tbl1

id    | OutPutValue  | 
1     | 2019         |
2     | 2018         |

tbl2

object_id      | status  |  type |
1              | 22      |  a    |
1              | 22      |  c    |
1              | 33      |  b    |
2              | 33      |  c    |
2              | 33      |  c    |
2              | 33      |  c    |

我想要得到的是:它必须从 tbl1 中选择所有 'OutPutValue',其中,在 tbl2 中,'type' 列应该是 c,而 'status' 列对于所有行必须具有相同的值,即 33。请注意tbl1的主键(id)是tbl2中的外键(object_id)。

从 tbl1 中选择列,如果,tbl2 中的所有行(tbl1 的 id 在 tbl2 中有多个行(基于 object_id))具有相同的 status 值,即 33 并且类型应该是 'c'。

OutPutValue    | Type   |  status  |
2018           | c      |  33      |

我尝试了以下解决方案,但它没有返回所需的输出:

SELECT a.OutPutValue FROM tbl1 a JOIN tbl2 b ON a.id = b.object_id WHERE b.Type =c
GROUP BY a.OutPutValue, b.status HAVING b.STATUS IN(33)

【问题讨论】:

  • 您能告诉我们您为解决此问题所做的尝试吗?
  • @Paul 用我尝试过的解决方案更新了问题

标签: sql sql-server


【解决方案1】:

尝试结合聚合:

SELECT
    t1.OutPutValue,
    MAX(t2.type) AS type,
    MAX(t2.status) AS status
FROM tbl1 t1
INNER JOIN tbl2 t2
    ON t1.id = t2.object_id
GROUP BY
    t1.id,
    t1.OutPutValue
HAVING
    MIN(t2.status) = MAX(t2.status) AND
    MAX(t2.status) = 33 AND
    MIN(t2.type) =  MAX(t2.type) AND
    MAX(t2.type) = 'c';

【讨论】:

  • 它也返回那些状态为 != 33 的行
  • @rohit 然后在HAVING 子句中添加一个条件来断言它。您的问题没有明确说明 status = 33 的要求。
【解决方案2】:

另一种解决方案可能如下:

SELECT T1.id, T1.outputvalue FROM tbl1 T1
JOIN ( 
     SELECT tbl2.*, MAX(type), MAX(status)
     FROM tbl2
     GROUP BY object_id
     HAVING 
          MIN(status) = MAX(status) AND
          MIN(type) = MAX(type)
) T2 ON T1.id = T2.object_id
WHERE T2.type = 'c'

编辑:我已经更新了我的查询以匹配一个特定的案例,这使得它与另一个答案非常相似。

FIND A DEMO HERE

【讨论】:

    【解决方案3】:

    您可以尝试使用相关子查询

    DEMO

    select distinct OutPutValue,type, status
    from t2 a inner join t1 b on a.object_id=b.id
    where type='c' and not exists 
          (select 1 from t2 a1 where a.object_id=a1.object_id and status<>33 and type='c')
    

    输出:

    OutPutValue type    status
    2018        c         33
    

    【讨论】:

    • 它也会返回那些类型为 != c 的行
    • @rohit,你能在提供的演示中给我看一下吗?
    • 您的解决方案有效,但实际上我正在尝试使用 type != value 然后选择,在这种情况下它不起作用。即类型不应该是“值”,选择休息
    • @rohit,你到底想做什么?
    猜你喜欢
    • 2020-01-04
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多