【问题标题】:How do you check for matching value in third column based on distinct combinations of other two columns?如何根据其他两列的不同组合检查第三列中的匹配值?
【发布时间】:2019-10-29 05:28:57
【问题描述】:

我有一个带有建筑物名称的表,例如 A、B、C。这些建筑物名称可以重复。我有另一个专栏有发言权。例如第 1 层,第 2 层。同样,每个建筑物都可以有多个第 1 层。第三列有对象存在,如电视、砖块、风扇。 我想检查建筑物与相应楼层的每个组合,例如 A 楼 - 1 楼,A 楼 - 2 楼,如果存在对象“砖”,则“墙”必须存在。

示例数据: 对于每个建筑物和位置,如果存在“WALL”,则必须存在“WINDOW”、“WINDOW1”或“WINDOW2”,ELSE FLAG

BUILDING  LOCATION  OBJECT   
A         FLOOR1    WALL
A         FLOOR1    WINDOW  
A         FLOOR2    WALL  
B         FLOOR1    WALL  
C         FLOOR1    WALL  
C         FLOOR1    WINDOW

期望的输出

BUILDING  LOCATION  ACTION  

A         FLOOR2    FLAG
B         FLOOR1    FLAG

我尝试过使用 GROUP BY、DISTINCT、WHERE EXISTS,但我似乎无法提出正确的逻辑。

【问题讨论】:

  • 更新您的问题添加清晰的数据样本和预期结果
  • @scaisEdge 添加
  • 结果中不应该是C而不是B吗?

标签: mysql mysql-workbench


【解决方案1】:

您可以group by building, location 为行where object in ('WALL', 'WINDOW')

select building, location, 'FLAG' action
from tablename
where object in ('WALL', 'WINDOW')
group by building, location
having count(distinct object) < 2

having 子句中的条件count(distinct object) &lt; 2 返回building, location 的组合,其中'WALL''WINDOW' 并不同时存在。
请参阅demo
结果:

| building | location | action |
| -------- | -------- | ------ |
| A        | FLOOR2   | FLAG   |
| B        | FLOOR1   | FLAG   |

或者不存在:

select t.building, t.location, 'FLAG' action
from tablename t
where object in ('WALL', 'WINDOW')
and not exists (
  select 1 from tablename
  where building = t.building and location = t.location and object <> t.object
)

请参阅demo

【讨论】:

  • 这可行,但我也更新了我的问题。如果您需要检查多个值怎么办?你会怎么做?
  • 这回答了原始问题。如果您还有其他问题,请发布。
【解决方案2】:

嵌套表是您想要的。类似的东西

select column_3
from (
  select *
  from table
  where table.column_3="brick"
) as e
join table t on t.id = e.id
where table.column_3="window"

fyi:我建议您以此作为开始,但对于您的具体情况,我想这需要修改

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    相关资源
    最近更新 更多