根据组中的值选择一行

时间:2017-11-14 01:14:39

标签: sql group-by subquery

新手SQL编码器在这里。我的数据如下:

Case          Allegation          Result
1             1                   Supported
1             2                   Not Supported
2             1                   Not Supported
3             1                   Not Supported
3             2                   Supported
3             3                   Not Supported
4             1                   Not Supported
4             2                   Supported

就我的目的而言,一个案例被视为"支持"如果其中的任何指控得到支持。我需要做的是每个唯一的Case返回一行,其中包含"支持"如果满足该条件,则读取"不支持":

Case          Result
1             Supported
2             Not Supported
3             Supported
4             Supported

在过去,我已经过度选择"我需要什么,并通过Reporting Services表达式完成显示工作,但这次我提供了一个查询。我想象我需要一个小组的子选择,但这并不是第一个如何做到这一点的想法。

3 个答案:

答案 0 :(得分:0)

这样的东西
Select 
   t.[case], 
   case when existSupported.case is not null then “Supported” else “Not Supported”
 From table1 t
    Left join (select distinct [case] from table1 where result = ‘Supported’) existsSupported 
  on t.case = existsSupported.case 

应该带你去那里

答案 1 :(得分:0)

CASE字段的GROUP
结果字段的最大值(其中S高于N)

declare @mytable table ([case] smallint, allegation smallint,result varchar(20))

insert into @mytable
values (1            , 1                 ,'Supported'),
(1           ,  2                   ,'Not Supported'),
(2          ,   1                   ,'Not Supported'),
(3        ,     1                   ,'Not Supported'),
(3       ,      2                   ,'Supported'),
(3      ,       3                   ,'Not Supported'),
(4     ,        1                   ,'Not Supported'),
(4     ,        2                   ,'Supported')



select [case], max(result) [Result]
 from @mytable
group by [case]

结果

1   Supported
2   Not Supported
3   Supported
4   Supported

答案 2 :(得分:0)

SELECT DISTINCT a.[case], 
            CASE 
              WHEN c.result IS NULL THEN 'Not Supported' 
              ELSE 'Supported' 
            END AS result 
FROM   t AS a 
   LEFT JOIN (SELECT b.[case], 
                     b.result 
              FROM   t AS b 
              WHERE  b.result = 'Supported') AS c 
          ON a.[case] = c.[case]; 

<强>结果:

case    result
1   Supported
2   Not Supported
3   Supported
4   Supported

你可以在这里看到:

http://sqlfiddle.com/#!6/9c217/47