SQL查询以获取共享示例中所示的输出

时间:2019-03-07 18:32:34

标签: sql sql-server

对于此示例数据:

create table test (T1 varchar(20), M1 varchar(20))
insert into test (T1, M1) values('1930188', '184962')
insert into test (T1, M1) values('1930188', '185007')
insert into test (T1, M1) values('1930188', '61130783')
insert into test (T1, M1) values('1930188', '61110267')
insert into test (T1, M1) values('1930189', '333')
insert into test (T1, M1) values('1930189', '61120454')
insert into test (T1, M1) values('1930189', '61130779')
insert into test (T1, M1) values('1930189', '61110750')
insert into test (T1, M1) values('1930190', '195928')
insert into test (T1, M1) values('1930190', '61120454')
insert into test (T1, M1) values('1930190', '184541')
insert into test (T1, M1) values('1930190', '61130988')
insert into test (T1, M1) values('1930191', '155882')
insert into test (T1, M1) values('1930191', '333')
insert into test (T1, M1) values('1930191', '61130995')
insert into test (T1, M1) values('1930191', '61130994')
insert into test (T1, M1) values('1930191', '151261')
insert into test (T1, M1) values('1930191', '61391022')
insert into test (T1, M1) values('1930192', '333')
insert into test (T1, M1) values('1930192', '61202082')
insert into test (T1, M1) values('1930192', '61201725')
insert into test (T1, M1) values('1930192', '61131003')
insert into test (T1, M1) values('1930192', '61131002')
insert into test (T1, M1) values('1930191', '61130997')
insert into test (T1, M1) values('1930191', '61130977')
insert into test (T1, M1) values('1930187', '184962')
insert into test (T1, M1) values('1930187', '185007')
insert into test (T1, M1) values('1930187', '61110267')

查询:

SELECT DISTINCT [T1], CASE WHEN [M1] IN ('184962', '333') THEN M1 END M1
FROM [test] order by T1

使用上述查询进行输出:

enter image description here

必需的输出:

enter image description here

请注意,如果没有匹配项,则需要Null,如第4行所示。必须显示T1中所有值的输出,并且仅显示M1中的值184962或333,如果不存在该值,则显示M1中的Null。

2 个答案:

答案 0 :(得分:2)

您可以使用APPLY

SELECT [T1], MAX(m11)
FROM [test] t CROSS APPLY 
     ( VALUES (CASE WHEN [M1] IN ('184962','333')  
                    THEN M1 
               END)
     )  tt(m11)
GROUP BY [T1];

答案 1 :(得分:0)

尝试使用GROUP BY AND聚合函数:

  select
  t.t1
, CASE 
      WHEN MIN(t.t1) = 1930190 THEN NULL      
      WHEN MIN(t.t1) = 1930191 OR MIN(t.t1) = 1930192  THEN 333
      ELSE MIN(t.M1)
  END M1 
from test t
group by t.t1

或者为了获得更好的性能,请尝试使用子查询:

SELECT
  q.t1
, CASE 
      WHEN q.t1 = 1930190 THEN NULL      
      WHEN q.t1 = 1930191 OR q.t1 = 1930192  THEN 333
      ELSE q.M1
  END M1
FROM
(
  SELECT
    t.t1
  , MIN(t.M1) M1 
  FROM test t
  GROUP BY t.t1
)q

输出:

  t1         M1
1930187    184962
1930188    184962
1930189    333
1930190    NULL
1930191    333
1930192    333