员工数据第一表
|ids| name |
+=============+
|1 | Ibrahim |
|2 | Rizky |
|3 | David |
第二个人上班
|id| ids | date |
+========+============+
|1 | 1 | 2018-05-01 |
|2 | 2 | 2018-05-01 |
|3 | 3 | 2018-05-01 |
|4 | 1 | 2018-05-02 |
|5 | 3 | 2018-05-02 |
|6 | 1 | 2018-05-03 |
|6 | 2 | 2018-05-03 |
|7 | 1 | 2018-05-04 |
|8 | 2 | 2018-05-04 |
|9 | 3 | 2018-05-04 |
我想要的结果或多或少是这样的
|name | 2018-05-01 | 2018-05-02 | 2018-05-03 | 2018-05-04 |
=========+============+============+==-=========+============+
|Ibrahim | 1 | 1 | 1 | 1 |
|Rizky | 1 | | 1 | 1 |
|David | 1 | 1 | | 1 |
您能帮我吗,我想显示这样的数据,以下日期为部分示例,我希望从第一个月到月底一个月。 1表示该人上班,空意味着不上班。
您能为我提供帮助吗,如何查询其联接以及如何在外观上显示迭代?
最佳答案
可能有一种很不错的方法,但是我会like this
select
e.name,
if(sum(if(w.date = '2018-05-01',1,0))=0,null,1) as '2018-05-01',
if(sum(if(w.date = '2018-05-02',1,0))=0,null,1) as '2018-05-02',
if(sum(if(w.date = '2018-05-03',1,0))=0,null,1) as '2018-05-03',
if(sum(if(w.date = '2018-05-04',1,0))=0,null,1) as '2018-05-04',
if(sum(if(w.date = '2018-05-05',1,0))=0,null,1) as '2018-05-05',
if(sum(if(w.date = '2018-05-06',1,0))=0,null,1) as '2018-05-06',
if(sum(if(w.date = '2018-05-07',1,0))=0,null,1) as '2018-05-07'
from employee e
left join work w ON e.ids = w.ids
group by e.ids
我对员工ID进行分组,并使用总和(if(来确定他们当天是否工作。
这是动态方法-
SET @s := (SELECT GROUP_CONCAT(DISTINCT CONCAT('if(sum(if(w.date = "',
date,
'",1,0))=0,null,1) AS `',
date,'`'
)
) from work);
SET @s := concat('select e.name, ',@s,' from employee e
left join work w ON e.ids = w.ids
group by e.ids');
PREPARE stmt FROM @s;
EXECUTE stmt;
有关动态方法available here的更多信息。
关于mysql - Mysql Join循环水平,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50596503/