1

我正在用 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

现在我只想从重复行/结果中选择一条记录,例如:Category-Emotional, condition-Depression which hasCondition '1' or 'true'

我希望我用这个例子说清楚了。请帮我。

谢谢。

4

2 回答 2

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
于 2012-10-18T13:38:31.703 回答
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
于 2012-10-18T13:40:20.773 回答