需求:
日志(info_log)里面包含多条录音记录(info_record)
员工表
info_user
user_id user_name
日志表
info_log
log_id user_id is_succ(成功1、失败0)
录音表
info_record
record_id log_id record_len
现需要统计每一个人员成功通话的长度、失败通话的长度、总的通话长度。下面是我使用的方法:
1.创建相关表
------创建用户信息表------------- IF EXISTS (SELECT * FROM sysobjects WHERE [name]='sys_user') DROP TABLE sys_user BEGIN CREATE TABLE sys_user( [user_id] INT IDENTITY(1,1) PRIMARY KEY NOT NULL, [user_name] NVARCHAR(20) NOT NULL ) END GO -----------创建日志表--------------------- IF EXISTS (SELECT * FROM sysobjects s WHERE [name]='info_log') DROP TABLE info_log BEGIN CREATE TABLE info_log ( log_id INT PRIMARY KEY IDENTITY(1,1) NOT NULL, [user_id] INT NOT NULL, is_success BIT --1成功,0--失败 ) END GO -----------创建录音表----------------------------- IF EXISTS (SELECT * FROM sysobjects s WHERE [name] ='info_record') DROP TABLE info_record BEGIN CREATE TABLE info_record( record_id INT PRIMARY KEY IDENTITY(1,1) NOT NULL, log_id INT NOT NULL, record_len FLOAT NOT NULL ) END GO
2.插入测试数据
BEGIN INSERT into sys_user ([user_name]) VALUES('Jack') INSERT into sys_user ([user_name]) VALUES('Tom') INSERT into sys_user ([user_name]) VALUES('Harry') INSERT into sys_user ([user_name]) VALUES('Potter') END GO --------------日志表插入数据---------------------- INSERT INTO info_log ([user_id],is_success) VALUES (1,1) INSERT INTO info_log ([user_id],is_success) VALUES (1,0) INSERT INTO info_log ([user_id],is_success) VALUES (2,1) INSERT INTO info_log ([user_id],is_success) VALUES (2,0) INSERT INTO info_log ([user_id],is_success) VALUES (3,1) INSERT INTO info_log ([user_id],is_success) VALUES (3,0) INSERT INTO info_log ([user_id],is_success) VALUES (4,1) INSERT INTO info_log ([user_id],is_success) VALUES (4,0) --------------插入录音数据----------------------------- INSERT info_record (log_id,record_len)VALUES(1,10.08) INSERT info_record (log_id,record_len)VALUES(2,11.18) INSERT info_record (log_id,record_len)VALUES(3,9.08) INSERT info_record (log_id,record_len)VALUES(4,8.2) INSERT info_record (log_id,record_len)VALUES(5,7.08) INSERT info_record (log_id,record_len)VALUES(6,2.08) INSERT info_record (log_id,record_len)VALUES(7,3.08) INSERT info_record (log_id,record_len)VALUES(8,5.08) INSERT info_record (log_id,record_len)VALUES(9,4.08) INSERT info_record (log_id,record_len)VALUES(10,5.08)
3.实现统计每一个人员成功通话的长度、失败通话的长度、总的通话长度
SELECT su.[user_name],SUM(CASE WHEN il.is_success=1 THEN ir.record_len ELSE 0 END ) AS '成功通话长度', sum(case when il.is_success=0 then ir.record_len else 0 end) as'失败通话长度', SUM(ir.record_len) AS '总通话长度' FROM sys_user su LEFT JOIN info_log il ON il.[user_id] = su.[user_id] LEFT JOIN info_record ir ON ir.log_id = il.log_id GROUP BY su.[user_name]
希望博友如有更好的方法,写下来探讨一下。