如何从另一个表中的一个表中搜索值?

时间:2014-07-07 18:32:28

标签: mysql sql pivot

我有一张存储一些员工姓名的表。

      ID              Name       
    -------------------------------
    01                  Mark
    02                  John
    03                  Macy
    04                  Drey
    05                  Ivan
    06                  Eduard 
    07                  Mary
    08                  Duley

我得到了一个数据透视表(请注意,键是已知的,但不是每个键都存储的值,例如日期):

      ID              Reference          Key               Value
    -------------------------------------------------------------
    01                  001             date                03/04/2009
    02                  001             shift               1st
    03                  001             station a           Mark
    04                  001             station b           John
    05                  001             station b           Macy
    06                  002             date                04/04/2009
    07                  002             shift               2nd
    08                  002             station a           John
    09                  002             Station a           Drey
    10                  002             Station b           Macy

我想拥有:

    Operator         Dates             1st Shift    2nd shift   A Station  B Station
    ---------+-----------------------+------------+------------+----------+--------
    Mark      03/04/2009                   2              0           1        0
    John      03/04/2009, 04/04/2013       1              1           1        1
    Macy      03/04/2009, 04/04/2009       1              1           0        2
    Drey      04/04/2009                   0              1           1        0

换句话说:"日期"专栏显示每个雇员工作的日子。其他列计算每个员工在每个站点和每个班次工作的次数。

如果查询适合视图,也会很棒....

很多!

1 个答案:

答案 0 :(得分:-1)

它不漂亮,在生产环境中执行可能需要相当长的时间,但是您的数据缺乏稳定的分组组件这一事实使得这样做很难有效。

所以,试试这个:

SELECT e.`Name`
  , (select group_concat(`Value`) from shiftinfo where `Key` = 'date' and Reference in (select Reference from shiftinfo where `Value` = e.`Name`)) as Dates
  , (select count(Reference) from shiftinfo where `Key` = 'shift' and `Value` = '1st' and Reference in (select Reference from shiftinfo where `Value` = e.`Name`)) as `1st Shift`
  , (select count(Reference) from shiftinfo where `Key` = 'shift' and `Value` = '2nd' and Reference in (select Reference from shiftinfo where `Value` = e.`Name`)) as `2nd Shift`
  , (select count(Reference) from shiftinfo where `Key` = 'station a' and `Value` = e.`Name`) as `Station A`
  , (select count(Reference) from shiftinfo where `Key` = 'station b' and `Value` = e.`Name`) as `Station B`
FROM employee e;

我们根据员工姓名选择部分原因,因为没有一种方法可以获得您想要的所有数据。

请参阅演示here on SQLFiddle