我在SQL中编写一个用于SSRS 2005的查询
select t1.Category, t2.condition,'1' as hasCondition from t1
left outer join t2 on t1.ID = t2.ID
left outer join t3 on t2.cID = t3.cID
where t3.clientID = 6
union
select t1.Category, t2.condition, '0' as hasCondition from t1
left outer join t2 on t1.ID = t2.ID
并将数据返回为:
Category Condition hasCondition
Behavioural Tourette's Syndrome 0
Communications Impaired Speech 0
Dexterity Osteoarthritus 0
Dexterity Osteoporosis 0
Dexterity Other Dexterity 0
Dexterity Rheumatoid Arthritus 0
Emotional Bipolar Disorder 0
Emotional Clinical Depression 0
Emotional Depression 0
Emotional Depression 1
Emotional Gulf War Syndrome 0
Emotional Gulf War Syndrome 1
现在我只想从重复行/结果中选择一条记录,例如: 类别 - 情绪,条件 - 抑郁,其中包含条件'1'或'真'
我希望我使用这个例子说清楚。 请帮帮我。
感谢。
答案 0 :(得分:0)
SELECT category, condition, MAX(hasCondition)
FROM (
select t1.Category, t2.condition,'1' as hasCondition from t1
left outer join t2 on t1.ID = t2.ID
left outer join t3 on t2.cID = t3.cID
where t3.clientID = 6
union
select t1.Category, t2.condition, '0' as hasCondition from t1
left outer join t2 on t1.ID = t2.ID)
GROUP BY category, condition
答案 1 :(得分:0)
这不是100%清楚你想要什么,但我认为你只是在寻找最终领域的MAX()......
SELECT
category, condition, MAX(has_condition) AS hasCondition
FROM
(
select t1.Category, t2.condition,'1' as hasCondition from t1
left outer join t2 on t1.ID = t2.ID
left outer join t3 on t2.cID = t3.cID
where t3.clientID = 6
union
select t1.Category, t2.condition, '0' as hasCondition from t1
left outer join t2 on t1.ID = t2.ID
)
AS data
GROUP BY
category, condition
如果您想简化整个查询......
select
t1.Category,
t2.condition,
MAX(CASE WHEN t3.clientID = 6 THEN 1 ELSE 0 END) as hasCondition
from
t1
left outer join
t2
on t2.ID = t1.ID
left outer join
t3
on t3.cID = t2.cID
and t3.clientID = 6
group by
t1.Category,
t2.condition