问题
I have a table with Building name, such as A, B, C. These building names could be repeated. I have another column which has the floor. Such as floor 1 ,floor 2. Again there could be multiple floor 1 for every building. There is a third column which has object present such as television, bricks, fans. I want to check for every combination of building with corresponding floors, such as Building A - floor 1, Building A- floor 2, if an object 'brick' exists then 'wall' must exist.
EXAMPLE DATA: For every building and location, if 'WALL' exists , 'WINDOW', 'WINDOW1' or 'WINDOW2' must exist, ELSE FLAG
BUILDING LOCATION OBJECT
A FLOOR1 WALL
A FLOOR1 WINDOW
A FLOOR2 WALL
B FLOOR1 WALL
C FLOOR1 WALL
C FLOOR1 WINDOW
DESIRED OUPUT
BUILDING LOCATION ACTION
A FLOOR2 FLAG
B FLOOR1 FLAG
I have tried using GROUP BY, DISTINCT, WHERE EXISTS, but I cant seem to come up with the right logic.
回答1:
You can group by building, location
for the rows 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
The condition count(distinct object) < 2
in the having
clause returns combination of building, location
where 'WALL'
and 'WINDOW'
do not both exist.
See the demo.
Results:
| building | location | action |
| -------- | -------- | ------ |
| A | FLOOR2 | FLAG |
| B | FLOOR1 | FLAG |
Or with NOT EXISTS:
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
)
See the demo.
回答2:
nested tables is what you want. Something like
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: I reccomend you use this as a start, but for your exact case, id imagine this needs to be modified
来源:https://stackoverflow.com/questions/56600496/how-do-you-check-for-matching-value-in-third-column-based-on-distinct-combinatio