[英]SQL - Aggregating data in a result set with identical rows and eliminating multiple rows based on one column's value
我有一个表,其中包含由TransactionTime按employeeID进行的事务。 每个员工可能有多个同时发生的交易。 例如:EmployeeID 1在12有2个事务。我需要在每个时间间隔按EmployeeID对事务进行求和。 因此,对于employeeID 1,新列(TotalTransactionsByTime)的结果将为2。接下来,如果给定TransactionTime的CODE的代码为BAD,则我需要排除该时间增量的所有事务。 因此,对于EmployeeID 2,我将需要从结果集中排除所有三个事务,因为它们的CODE为“ BAD”,该代码以该增量使所有事务无效。
我的桌子
|EmployeeID|TransactionTime|CODE|
1 12 GOOD
1 12 GOOD
1 5 GOOD
2 1 BAD --need to omit all 3 transactions for employeeID 2
2 1 GOOD
2 1 GOOD
3 3 GOOD
3 3 GOOD
A correct result would look like:
|EmployeeID | TransactionTime | CODE | NUMBERTRNS
1 12 GOOD | 2
1 5 GOOD | 1
3 3 GOOD | 2
select mt1.EmployeeID, mt1.TransactionTime, mt1.CODE, count(*) as NUMBERTRNS
from MyTable mt1
where mt1.EmployeeID not in (select EmployeeID from MyTable where CODE = 'BAD')
group by mt1.EmployeeID, mt1.TransactionTime, mt1.CODE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.