问题: 有两列。 column1和column2 第1列可能有一些类似的数据(任务),而第2列则根据用户是否分配给该任务的结果为true和false。
我想按值分组,看看是否在同一任务(第1列)中甚至有1个假,然后也将其他类似的任务也假。
有人可以帮我吗?
Value |PrimaryOwnerId
_______________________________________________________________________
EVP-RP&P | true
Execution Coordinator | true
Execution Coordinator | flase
Inspection Lead | true
Instrument, Electrical, and Analyzer | true
Logistics | true
Logistics | flase
Operations | true
Planning | true
我正在使用此查询。
select CraftName AS value,
case
when PrimaryOwnerID is Null
Then 'true'
else 'flase'
End as PrimaryOwnerID
FROM EventTasks AS et
INNER JOIN EventMileStones AS em ON em.EventMileStoneID = et.EventMileStoneID
INNER JOIN LocationTasks AS lt ON lt.LocationTaskID = et.LocationTaskID
INNER JOIN Crafts AS c ON c.ID = lt.CraftID
WHERE ProjectID = 4
group by CraftName, PrimaryOwnerID
答案 0 :(得分:0)
对查询使用CTE,然后使用EXISTS检查值是否存在不为null的PrimaryOwnerID:
with cte as (
select
CraftName AS value,
PrimaryOwnerID,
FROM EventTasks AS et
INNER JOIN EventMileStones AS em ON em.EventMileStoneID = et.EventMileStoneID
INNER JOIN LocationTasks AS lt ON lt.LocationTaskID = et.LocationTaskID
INNER JOIN Crafts AS c ON c.ID = lt.CraftID
WHERE ProjectID = 4
GROUP BY CraftName, PrimaryOwnerID
)
select
c.value,
case
when exists (
select 1 from cte where value = c.value and PrimaryOwnerID is not null
) then 'false'
else 'true'
end PrimaryOwnerID
from cte c
答案 1 :(得分:0)
我认为窗口函数更简单。因为您使用的是字符串,所以min()
符合您的逻辑:
select CraftName AS value,
min(PrimaryOwnerID) over (partition by CraftName) as new_PrimaryOwnerID
from EventTasks et join
EventMileStones em
on em.EventMileStoneID = et.EventMileStoneID join
LocationTasks lt
on lt.LocationTaskID = et.LocationTaskID join
Crafts c
on c.ID = lt.CraftID
where ProjectID = 4
group by CraftName, PrimaryOwnerID;
不需要子查询或CTE。