mysql - 在 MySQL 上排列数据
问题描述
有什么办法可以安排这种输出吗?
我希望日期时间和状态在另一列上分开
输出应该是这样的:
company_id | 姓名 | 日期时间 C/In | 状态 C/In | 日期时间 C/Out | 状态 C/Out
谢谢
解决方案
假设没有人在午夜工作,您可以按公司、员工、日期汇总,使用工会捕获任何已退出但未登录的人。例如
drop table if exists t;
create table t
(company int, employee int, dt datetime , state varchar(5));
insert into t values
(1,1,'2020-03-01 08:00:01','cin'),
(1,1,'2020-03-01 08:00:02','cin'),
(1,1,'2020-03-01 08:00:03','cout'),
(1,1,'2020-03-02 08:00:01','cin'),
(1,1,'2020-03-02 08:00:02','cout'),
(1,1,'2020-03-02 08:00:03','cout'),
(1,1,'2020-03-03 08:00:01','cin'),
(1,1,'2020-03-04 08:00:01','cout')
;
select company,employee,'cin', min(dt) cin,'cout',
(select max(dt)
from t t1
where t1.company = t.company and
t1.employee = t.employee and
date(t1.dt) = date(t.dt) and
state = 'cout') cout
from t
where state = 'cin'
group by company,employee,date(dt)
union all
select company,employee,'cin', null cin,
'cout', max(dt)
from t
where state = 'cout' and
(select min(dt)
from t t1
where t1.company = t.company and
t1.employee = t.employee and
date(t1.dt) = date(t.dt) and
state = 'cin') is null
group by company,employee,date(dt);
+---------+----------+-----+---------------------+------+---------------------+
| company | employee | cin | cin | cout | cout |
+---------+----------+-----+---------------------+------+---------------------+
| 1 | 1 | cin | 2020-03-01 08:00:01 | cout | 2020-03-01 08:00:03 |
| 1 | 1 | cin | 2020-03-02 08:00:01 | cout | 2020-03-02 08:00:03 |
| 1 | 1 | cin | 2020-03-03 08:00:01 | cout | NULL |
| 1 | 1 | cin | NULL | cout | 2020-03-04 08:00:01 |
+---------+----------+-----+---------------------+------+---------------------+
4 rows in set (0.002 sec)
推荐阅读
- java - 如何获取显示文本:硒中的无元素
- regex - 如何限制 apache 不发送任何 csv、txt、log、sh 文件作为响应
- c++11 - 使用Botan从私钥中提取公钥
- sql-server - 在Entity Framework中配置模型时ForSqlServerHasIndex和HasIndex有什么区别
- python - 有没有办法在 azure python sdk api 中获取 vm 的 vcpu 数量?
- r - R 中 sqldf 中的 min(date) 未转换为日期格式
- hibernate - 带有谓词的条件生成器
- uipath - 如何使用带有 UIPATH 的 Excel 迭代 SAP 表并单击每一行?
- javascript - 是否可以在 TypeScript 中使用类型化流?
- jenkins - 在管道中使用 Jenkins 全局凭证 (Jenkinsfile)