【问题标题】:Mysql Query using Pivot tableMysql 使用数据透视表查询
【发布时间】:2017-12-19 05:15:10
【问题描述】:

我有 ff。数据..

empID 登录日期 TimeIN 超时 1001 01/01/2017 08:00 17:00 1001 2017 年 1 月 2 日 07:59 17:02 1001 2017 年 1 月 3 日 07:54 17:05 1001 2017 年 1 月 4 日 08:00 17:04 1001 01/05/2017 07:56 17:03 1001 2017 年 1 月 6 日 07:52 17:01 1001 2017 年 1 月 7 日 07:53 17:02

我希望输出是这样的..

EmpID 周一 周二 周三 周四 周五 1001 08:00-17:00 7:59-17:02 07:54-17:05 08:00-17:04 07:56-17:03

我已尝试使用此查询..

选择 cEmpID,dDate, (case DAYOFWEEK(dDate) WHEN 1 then CONCAT(cIn1,' - ',cOut2) else '' End) as 'Mon', (case DAYOFWEEK(dDate) WHEN 2 then CONCAT(cIn1,' - ',cOut2) else '' End) as 'Tue', (case DAYOFWEEK(dDate) WHEN 3 then CONCAT(cIn1,' - ',cOut2) else '' End) as 'Wed', (case DAYOFWEEK(dDate) WHEN 4 then CONCAT(cIn1,' - ',cOut2) else '' End) as 'Thu', (case DAYOFWEEK(dDate) WHEN 5 then CONCAT(cIn1,' - ',cOut2) else '' End) as 'Fri', (case DAYOFWEEK(dDate) WHEN 6 then CONCAT(cIn1,' - ',cOut2) else '' End) as 'Sat', (case DAYOFWEEK(dDate) WHEN 7 then CONCAT(cIn1,' - ',cOut2) else '' End) as 'Sun' 来自 tblattenddetail 其中 cPeriodID='201702' 按 cEmpID 分组

但它不起作用..

【问题讨论】:

  • 当您不想将 dDate 放入结果中时,为什么要将它拉到选择列表中?
  • 检查这个答案,https://stackoverflow.com/questions/42408465/need-to-convert-columns-into-rows-in-mysql/42409047#42409047
  • @chiragsatapara,这个查询只能通过使用大小写来解决。此处无需使用枢轴。

标签: mysql pivot


【解决方案1】:

请尝试以下查询 -

SELECT empID,  
       MAX(case DAYOFWEEK(`Login Date`) WHEN 1 then CONCAT(TimeIN,' - ',TimeOut) else '' End) as 'Mon',
       MAX(case DAYOFWEEK(`Login Date`) WHEN 2 then CONCAT(TimeIN,' - ',TimeOut) else '' End) as 'Tue',
       MAX(case DAYOFWEEK(`Login Date`) WHEN 3 then CONCAT(TimeIN,' - ',TimeOut) else '' End) as 'Wed',
       MAX(case DAYOFWEEK(`Login Date`) WHEN 4 then CONCAT(TimeIN,' - ',TimeOut) else '' End) as 'Thu',
       MAX(case DAYOFWEEK(`Login Date`) WHEN 5 then CONCAT(TimeIN,' - ',TimeOut) else '' End) as 'Fri',
       MAX(case DAYOFWEEK(`Login Date`) WHEN 6 then CONCAT(TimeIN,' - ',TimeOut) else '' End) as 'Sat',
       MAX(case DAYOFWEEK(`Login Date`) WHEN 7 then CONCAT(TimeIN,' - ',TimeOut) else '' End) as 'Sun'  
FROM login
GROUP BY empID

这是供您参考的小提琴 - http://www.sqlfiddle.com/#!9/437e5/5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-03
    • 2012-12-31
    • 1970-01-01
    • 2017-02-20
    • 2015-09-30
    • 2014-01-07
    • 2018-12-08
    • 2021-06-13
    相关资源
    最近更新 更多