SQL查询以下情况的多行

时间:2019-09-24 16:34:22

标签: sql sql-server

需要根据所附图像中的预期结果列进行响应。 多行需要行过滤

enter image description here

规则是(x.attr2 ='1'AND x.attr3 ='1')AND(x.attr2 =''AND x.attr3 ='2')然后其预期的列值为true,但其他所有列条件为假

其MS SQL

Key Atr2    Atr3    expected result
111  1       1      TRUE
111  2       2  
112  1       4      FALSE
113  1       4      FALSE
113  2       2  
114  1       1      FALSE

2 个答案:

答案 0 :(得分:0)

此查询:

select key from tablename
group by key
having sum(case when atr2 = '1' and atr3 = '1' then 1 else 0 end) > 0
   and sum(case when atr2 = '2' and atr3 = '2' then 1 else 0 end) > 0
   and count(*) = 2

使用条件聚合来查找结果应为true的键。
因此,将其像这样加入到表中:

select t.*, 
  case when g.[key] is null then 'FALSE' else 'TRUE' end result
from tablename t left join (
  select [key] from tablename
  group by [key]
  having sum(case when atr2 = '1' and atr3 = '1' then 1 else 0 end) > 0
     and sum(case when atr2 = '2' and atr3 = '2' then 1 else 0 end) > 0
     and count(*) = 2
) g on g.[key] = t.[key]

请参见demo
结果:

> Key | Atr2 | Atr3 | result
> --: | ---: | ---: | :-----
> 111 |    1 |    1 | TRUE  
> 111 |    2 |    2 | TRUE  
> 112 |    1 |    4 | FALSE 
> 113 |    1 |    4 | FALSE 
> 113 |    2 |    2 | FALSE 
> 114 |    1 |    1 | FALSE

答案 1 :(得分:0)

检查以下脚本-

IF OBJECT_ID('[Sample]') IS NOT NULL
    DROP TABLE [Sample]

CREATE TABLE [Sample]
(
[Key] INT NOT NULL,
Attr1 INT NOT NULL,
Attr2 INT NOT NULL,
Attr3 INT NOT NULL
)
GO

INSERT INTO [Sample] ([Key],Attr1,Attr2,Attr3)
VALUES (111,62,1,1),
(111,62,2,2),
(112,62,1,4),
(113,62,1,4),
(113,62,2,2),
(114,62,1,1)

--EXPECTED_RESULT:
SELECT S.*,CASE WHEN T.[KEY] IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END AS Expected_Result 
FROM [Sample] S LEFT JOIN
( 
SELECT T.[KEY] FROM
(
SELECT x.*,
ROW_NUMBER() OVER( PARTITION BY x.[KEY],x.attr1 ORDER BY x.attr2,x.attr3) AS r_no
--,CASE WHEN (x.attr2 = 1 AND x.attr3 = 1) OR (x.attr2 = 2 AND x.attr3 = 2) 
--then 'TRUE' else 'FALSE' end as expected_result
FROM [Sample] x WHERE x.attr2=x.attr3
) T WHERE T.r_no>1
) T ON S.[KEY]=T.[KEY]