mysql - 获取其他表中的4个计数器(MYSQL)

标签 mysql sql

在我的时间表中有 1 , 2 , 3 ,4 计数器,我的问题是计数器 2 , 3 , 4 没有结果,但在我的计数器 1 中有一个输出(我这里有一些图片。)这是输出

Output 1

这是我的另一张 table my table

SELECT id,effectiveDate,      
      if(note = 'REGULAR LOGGED' and counter='1',log,'') as am1,
      if(note = 'REGULAR LOGGED' and counter='2',log,'') as am2,
      if(note = 'REGULAR LOGGED' and counter='3',log,'') as am3,
      if(note = 'REGULAR LOGGED' and counter='4',log,'') as am4
    FROM schedules as sch
    LEFT JOIN (SELECT empid,counter,note,log,id,date FROM timesheet) tim ON sch.empid = tim.empid and sch.effectiveDate = tim.date WHERE sch.empid='16'
    AND YEAR(effectiveDate) = YEAR(CURDATE()) and MONTH(effectiveDate) = MONTH(CURDATE())
GROUP BY effectiveDate

最佳答案

使用聚合函数:

SELECT effectiveDate,      
       max(case note = 'REGULAR LOGGED' and counter = 1 then log end) as am1,
       max(case note = 'REGULAR LOGGED' and counter = 2 then log end) as am2,
       max(case note = 'REGULAR LOGGED' and counter = 3 then log end) as am3,
       max(case note = 'REGULAR LOGGED' and counter = 4 then log end) as am4
FROM schedules s LEFT JOIN
     timesheet t
     ON s.empid = t.empid and s.effectiveDate = t.date
WHERE s.empid = 16 AND
      YEAR(effectiveDate) = YEAR(CURDATE()) AND
      MONTH(effectiveDate) = MONTH(CURDATE())
GROUP BY effectiveDate

关于mysql - 获取其他表中的4个计数器(MYSQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46630613/

相关文章:

php - 使用变量构建 Laravel 查询

php - 在 cake php 中从 db 获取最新保存的文件版本

sql - MySQL 通配符 * 和 %

java - 从 Hibernate 子列表结果

python - 需要在按不匹配日期分组的 2 个索引上转置一些 SQL 值(SQL 和 Python)

SQL查询某个日期范围内匹配日期的记录数?

mysql - mySQL如何确定TIMESTAMP字段的时区?

sql - 如何在 SQL WHERE IN 语句中使用 R 中的字符串

android - 如果我们将 android 中的 Room DB 中的列类型 TEXT NOT NULL 更改为 TEXT,如何添加迁移

sql - 根据日期选择最近的记录