mySQL选择查询语句

时间:2016-10-30 15:03:20

标签: mysql

在我的表中出席

Insert Into tblAttendance(cEmpID,cCode,dDate,notMin) Values
('1000','R' , 120,'2016-10-27'),
('1000','R' , 120,'2016-10-28'),
('1000','S' , 120,'2016-10-29'),
('1000','L' , 120,'2016-10-30'),
('1001','R' , 120,'2016-10-27'),
('1001','R' , 120,'2016-10-28'),
('1001','S' , 120,'2016-10-29'),
('1001','L' , 120,'2016-10-30')

我需要总结所有OT Min。每个代码 这样的输出...... 的EmpID,R-总计,S-总计,L-总计

这是我的样本查询

Select (Select sum(nOTMin) from tblattenddetail Where cCode='R') 'R-Total',
       (Select sum(nOTMin) from tblattenddetail Where cCode='S') 'S-Total',
       (Select sum(nOTMin) from tblattenddetail Where cCode='L') 'L-Total'

我需要包含cEmpID .. 请帮助我如何修改它以包括cEmpID ..

1 个答案:

答案 0 :(得分:1)

您可以使用案例表达式有条件地聚合正确的值。这应该做你想要的:

SELECT
  cEmpID, 
  SUM(CASE WHEN cCode='R' THEN nOTMin ELSE 0 END) AS 'R-Total',
  SUM(CASE WHEN cCode='S' THEN nOTMin ELSE 0 END) AS 'S-Total',
  SUM(CASE WHEN cCode='L' THEN nOTMin ELSE 0 END) AS 'L-Total'
FROM tblAttendance
GROUP BY cEmpID

Sample SQL Fiddle