T-SQL:
下面是我需要在col上应用逐行过滤器的表。
我的标准是Val应当为:0 AND(1或1.1)AND 2
原始表格是
name val
aaa 0
aaa 1
aaa 1.1
aaa 2
bbb 0
bbb 2
ccc 0
ccc 1
ccc 2
预期结果将
name val
aaa 0
aaa 1
aaa 1.1
aaa 2
ccc 0
ccc 1
ccc 2
任何人都可以提出解决方案。我正在尝试Where子句,但无法在where子句中提供条件。 感谢任何帮助
答案 0 :(得分:1)
满足条件时,以下内容将返回该组中的所有行:
DECLARE @test TABLE(
name varchar(10) NOT NULL
, value varchar(10) NOT NULL
);
INSERT INTO @test(name, value)
VALUES
('aaa', '0')
,('aaa', '1')
,('aaa', '1.1')
,('aaa', '2')
,('bbb', '0')
,('bbb', '2')
,('ccc', '0')
,('ccc', '1')
,('ccc', '2');
SELECT a.name, a.value
FROM @test a
CROSS APPLY(SELECT COUNT(*) FROM @test b WHERE b.name = a.name AND value IN('0', '2')) AS b(cnt)
CROSS APPLY(SELECT COUNT(*) FROM @test b WHERE b.name = a.name AND value IN('1', '1.1')) AS c(cnt)
WHERE b.cnt = 2 AND c.cnt >= 1;
答案 1 :(得分:0)
将这3个条件指定为cte并连接到原始表。匹配的行应为3
; with
-- your table
tbl as
(
select name = 'aaa', val = 0 union all
select name = 'aaa ', val = 1 union all
select name = 'aaa', val = 1.1 union all
select name = 'aaa', val = 2 union all
select name = 'bbb', val = 0 union all
select name = 'bbb', val = 2 union all
select name = 'ccc', val = 0 union all
select name = 'ccc', val = 1 union all
select name = 'ccc', val = 2
),
-- your condition
val as
(
select val1 = 0, val2 = 0 union all
select val1 = 1, val2 = 1.1 union all
select val1 = 2, val2 = 2
),
cte_name as
(
select t.name
from tbl t
inner join val v on t.val = v.val1
or t.val = v.val2
group by name
having count(distinct v.val1) = 3 -- matching rows should be 3
)
-- the query
select t.*
from tbl t
inner join cte_name n on t.name = n.name
答案 2 :(得分:0)
另一个版本:
DECLARE @test TABLE(
name varchar(10) NOT NULL
, value decimal(5,1) NOT NULL
);
INSERT INTO @test(name, value)
VALUES
('aaa', 0)
,('aaa', 1)
,('aaa', 1.1)
,('aaa', 2)
,('bbb', 0)
,('bbb', 2)
,('ccc', 0)
,('ccc', 1)
,('ccc', 2);
select a.name, a.value
from @test a
join (
select name,
sum(case when value IN(0,2) then 1 else 0 end) as c02,
sum(case when value IN(1,1.1) then 1 else 0 end) as c1
from @test group by name
) g on g.name=a.name and c02=2 and c1>=1