SQL查询 - 我感到难过......排除记录

时间:2017-04-28 15:29:42

标签: sql

请参阅附加的法师,这是7天内员工的记录。如果每列(ST,OT,DT,PayPerdiem,PayTruck,PayTravel)的所有7条记录的总和等于零,我想要做的是排除所有员工记录(7)。

基本上,如果任何一个总数大于0,我想要雇员的所有7条记录,并且所有雇员总数的记录都不等于0。

因此,员工ATES不应返回任何记录,但员工BEADLING应返回7条记录。

这有意义吗?有人可以帮忙吗?这是为了提供一个数据透视表,经过几天的尝试,我根本想不出来。请帮忙。

enter image description here

3 个答案:

答案 0 :(得分:1)

您可以返回员工的所有记录,其中该员工的至少一行使用0的值大于exists(),如下所示:

select *
from t
where exists (
  select 1
  from t i
  where i.Employee = t.Employee
    and (
         st > 0
      or ot > 0
      or dt > 0
      or payperdiem > 0
      or paytruck   > 0
      or paytravel  > 0
      )
   )

rextester演示:http://rextester.com/VOOH64182

对于此示例数据:

create table t (Employee int, calendardate date, st int, ot int, dt int, payperdiem int, paytruck int, paytravel int)
insert into t values
 (1,'20170401',0,0,0,0,0,0)
,(1,'20170402',0,0,0,0,0,0)
,(1,'20170403',0,0,0,0,0,0)
,(1,'20170404',2,0,0,0,0,0) /* this one has a value */
,(2,'20170401',0,0,0,0,0,0)
,(2,'20170402',0,0,0,0,0,0)
,(2,'20170403',0,0,0,0,0,0)
,(2,'20170404',0,0,0,0,0,0)

返回:

+----------+--------------+----+----+----+------------+----------+-----------+
| Employee | calendardate | st | ot | dt | payperdiem | paytruck | paytravel |
+----------+--------------+----+----+----+------------+----------+-----------+
|        1 | 2017-04-01   |  0 |  0 |  0 |          0 |        0 |         0 |
|        1 | 2017-04-02   |  0 |  0 |  0 |          0 |        0 |         0 |
|        1 | 2017-04-03   |  0 |  0 |  0 |          0 |        0 |         0 |
|        1 | 2017-04-04   |  2 |  0 |  0 |          0 |        0 |         0 |
+----------+--------------+----+----+----+------------+----------+-----------+

答案 1 :(得分:1)

如果您有负值,则可能需要比较SUM

 SELECT t1.*
 FROM t as t1
 JOIN (SELECT Employee
       FROM t 
       GROUP BY Employee
       HAVING SUM(st) > 0
           OR SUM(ot) > 0
           OR SUM(dt) > 0
           OR SUM(payperdiem) > 0
           OR SUM(paytruck)   > 0
           OR SUM(paytravel)  > 0
      ) as t2
   ON t1.Employee = t2.Employee

答案 2 :(得分:1)

请尝试以下方法......

SELECT CalendarDate,
       tblTable.Employee,
       PayCodeName,
       ST,
       OT,
       DT,
       PayPerdiem,
       PayTruck,
       PayTravel
FROM tblTable
JOIN ( SELECT Employee
       FROM tblTable
       GROUP BY Employee
       HAVING SUM( ST +
                   OT +
                   DT +
                   PayPerdiem +
                   PayTruck +
                   PayTravel ) > 0
     ) EmployeeFinder ON tblTable.Employee = EmployeeFinder.Employee
ORDER BY tblTable.Employee,
         CalenadrDate;

此声明首先将tblTable中的每条记录按Employee分组,然后将该列表优化为总计所有总计字段大于0的组。

然后对带有INNER JOIN的结果数据集执行tblTable,这样可以消除Employee中未出现在子查询结果中的任何记录。

然后选择tblTable的幸存记录的字段并对记录进行排序。

如果您有任何问题或意见,请随时发表评论。