select * transform row value作为表列名

时间:2013-02-08 04:38:42

标签: mysql select group-concat

我正在尝试将行值转换为列名。在stackoverflow上搜索后,我了解到可以使用GROUP_CONCAT()完成。我尝试了但没有结果。

我想要什么?

我有一张这样的桌子:

id  |    staff_id_staff     |   leave_type_id_leave_type    |    days
1   |    41                 |   Casual                      |    7
2   |    41                 |   Earned                      |    1
3   |    41                 |   Sick                        |    4

并想要这样的结果:

Casual    |    Earned   |   Sick
7         |       1     |   4

请注意:我不知道leave_type_id_leave_type的价值(它会是什么)

以下是leave_remain表的代码:

CREATE TABLE IF NOT EXISTS `leave_remain` (
  `id_leave_remain` int(11) NOT NULL AUTO_INCREMENT,
  `staff_id_staff` int(11) NOT NULL,
  `leave_type_id_leave_type` int(11) NOT NULL,
  `days` float DEFAULT NULL,
  `updated` date DEFAULT NULL,
  PRIMARY KEY (`id_leave_remain`),
  UNIQUE KEY `leave_type_id_leave_type_UNIQUE` (`leave_type_id_leave_type`),
  KEY `fk_leave_remain_staff1` (`staff_id_staff`),
  KEY `fk_leave_remain_leave_type1` (`leave_type_id_leave_type`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=108 ;

--
-- Dumping data for table `leave_remain`
--

INSERT INTO `leave_remain` (`id_leave_remain`, `staff_id_staff`, `leave_type_id_leave_type`, `days`, `updated`) VALUES
(82, 41, 16, 16, '2013-02-04'),
(89, 41, 17, 178, '2013-02-06'),
(107, 41, 18, 0, '2013-02-04');

3 个答案:

答案 0 :(得分:3)

看到你需要处理与此查询类似的事情:

SELECT GROUP_CONCAT(CONVERT(leave_type_id_leave_type,char(10)))
FROM leave_remain
GROUP BY staff_id_staff
UNION
SELECT GROUP_CONCAT(CONVERT(days,char(10)))
FROM leave_remain
GROUP BY staff_id_staff

SqlFiddle

上查看演示

答案 1 :(得分:1)

尝试以下代码

SELECT 
max(DECODE(leave_type_id_leave_type,'Casual',days)) Casual,
max(DECODE(leave_type_id_leave_type,'Earned',days)) Earned,
max(DECODE(leave_type_id_leave_type,'Sick',days)) Sick
FROM table_name;

答案 2 :(得分:-1)

  select leave_type_id_leave_type,days,  
count(case when leave_type_id_leave_type = 'Casual' THEN 1 END) Casual,
count(case when leave_type_id_leave_type = 'Earned' THEN 1 END) Earned,
count(case when leave_type_id_leave_type = 'Sick' THEN 1 END) Sick 
from leave_remain GROUP BY id_leave_remain

请参阅SqlFiddle