根据组内的单行值选择组?

时间:2019-04-17 15:35:47

标签: sql tsql reporting-services

我正在处理薪资数据,我只想提取有加班费的支票。带有加班费的支票将有一行显示工资代码“ 5”。我知道我可以过滤并带回其中包含“ 5”的行,但是我需要排位检查中的所有行,而不仅是其中包含“ 5”的行。

这是数据的基本示例:

ROW  CHKNUM  PAYCODE  AMOUNT
1    000010     1        $15
2    000010     1N       $20
3    000010     5        $25
4    000011     1        $15
5    000011     1N       $20
6    000012     1        $15
7    000012     5        $25
8    000013     1        $15
9    000014     1        $15
10   000014     5N       $30

我需要返回支票号10、12和14的所有行,因为该支票号包含'5'支付代码。 (还需要所有以5结尾的付款代码)

3 个答案:

答案 0 :(得分:2)

您可以使用exists

select t.*
from table t
where exists (select 1 from table t1 where t1.chknum = t.chknum and t1.paycode like '5%');

答案 1 :(得分:0)

这将更加简单:

select * from Table1 where "CHKNUM" in(select "CHKNUM" from Table1 where 
regexp_like("PAYCODE",'(.)*5(.)*'));

检查http://sqlfiddle.com/#!4/6acf0/4

对于tsql来说,像这样:

select * from Table1 where "CHKNUM" in(select "CHKNUM" from Table1 
where PATINDEX ('(.)*5(.)*',"PAYCODE")=0);

http://sqlfiddle.com/#!18/66036/3

使用此:

 select * from Table1 where "CHKNUM" in(select "CHKNUM" from Table1 
 where "PAYCODE" like '5%');

http://sqlfiddle.com/#!18/66036/5

答案 2 :(得分:0)

这应该足够了:

SELECT * FROM #Payroll
WHERE CHKNUM in (select CHKNUM from #Payroll where PAYCODE like '5%')